package algorithm.apps;
import utils.com.Swapper;
/**
* 在数组中找第k小元素
*
* @author Toy
*
*/
public class Select_K_01 {
public int partition(int[] a, int left, int right) {
int ck = a[left];
int i = left + 1;
int j = right;
while (true) {
while (a[i] < ck) {
i++;
}
while (a[j] > ck) {
j--;
}
if (i >= j) {
break;
}
Swapper.swap(a, i, j);
i++;
j--;
}
a[left] = a[j];
a[j] = ck;
return j;
}
public int select_K_01(int[] a, int left, int right, int k) {
if (left == right) {
return a[left];
}
int p = partition(a, left, right);
int ck = p - left + 1;
// System.out.println(left+" "+a[left]+" "+p+" "+ck+" "+k);
if (ck >= k) {
return select_K_01(a, left, p, k);
} else {
return select_K_01(a, p + 1, right, k - ck);
}
}
/**
* @param args
*/
public static void main(String[] args) {
int[] a = new int[] { 1, 2, 3, 4, 5, 6 };
Select_K_01 s = new Select_K_01();
int k = 6;
int m = s.select_K_01(a, 0, a.length - 1, k);
System.out.println("method 01: " + m);
}
}