快排找数组中第k小元素

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
public kth{
public static Comparable select(Comparable[] a, int k){
StdRandom.shuffer(a);
int lo = 0;
int hi = a.length-1;
while (hi > lo){
int j = partition(a,lo,hi);
if (j == k) return a[k];
else if (j > k) hi = j - 1;
else lo = j + 1;
}
return a[k];
}
int patition(Comparable[] a, int lo, int hi){
int i = lo;
int j = hi;
Comparable v = a[lo];
while (true){
while (a[++i] < v) if (i == hi) break;
while (a[--j] > v) if (j == lo) break;
if (i >= j) break;
exc(a,i,j);
}
exc(a,lo,j);
return j;
}
void exc (Comparable[] a, int i, int j){
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
}