-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSelect.java
More file actions
29 lines (27 loc) · 822 Bytes
/
QuickSelect.java
File metadata and controls
29 lines (27 loc) · 822 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import static agt.algo.Utils.swap;
public class QuickSelect {
public static int quickSelect(int[] arr, int start, int end, int k) {
if (start == end) {
return arr[start];
}
int p = partition(arr, start, end);
int rank = p - start + 1;
if (rank == k) {
return arr[p];
} else if (rank > k) {
return quickSelect(arr, start, p - 1, k);
} else {
return quickSelect(arr, p + 1, end, k - rank);
}
}
private static int partition(int[] arr, int start, int end) {
int pivot = arr[end], p = start - 1;
for (int i = start; i <= end - 1; i++) {
if (arr[i] < pivot) {
swap(arr, ++p, i);
}
}
swap(arr, ++p, end);
return p;
}
}