-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBM47.java
More file actions
60 lines (55 loc) · 1.58 KB
/
BM47.java
File metadata and controls
60 lines (55 loc) · 1.58 KB
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package NiukeTOP101;
public class BM47 {
public int findKth(int[] a, int n, int K) {
return quickSort(a, 0, a.length - 1, K);
}
private int quickSort(int[] arr, int left, int right, int k) {
int p = partition(arr, left, right);
if(p == arr.length - k){
return arr[p];
}
else if(p < arr.length - k){
return quickSort(arr, p + 1, right, k);
}
else{
return quickSort(arr, left, p - 1, k);
}
}
private int partition(int[] arr, int left, int right){
int key = arr[left];
while(left < right){
while (left < right && arr[right] >= key){
right --;
}
arr[left] = arr[right];
while (left < right && arr[left] <= key){
left ++;
}
arr[right] = arr[left];
}
arr[right] = key;
return left;
}
}
class QuickSort{
public void quickSort(int[] arr, int left, int right){
int anchor = partition(arr, left, right);
quickSort(arr, left, anchor - 1);
quickSort(arr, anchor + 1, right);
}
private int partition(int[] arr, int left, int right){
int point = arr[left];
while (left < right){
while (left < right && arr[right] >= point){
right --;
}
arr[left] = arr[right];
while (left < right && arr[left] <= point){
left ++;
}
arr[right] = arr[left];
}
arr[right] = point;
return left;
}
}