类似于快速排序,执行一次快速排序之后,每次只选择一部分继续执行快速排序,直到找到第K大个元素为止,这个元素在数组位置后面的元素即为所求。
利用快速排序子过程的返回哨兵的位置,将哨兵的序号和k - 1进行比较
时间复杂度:O(n)
public class Quick_find {
public static int sort(int[] array, int low, int high) {
if (low > high)
return -1;
int key = array[low];
while (low < high) {
while (array[high] > key && high > low)
high--;
array[low] = array[high];
while (array[low] < key && high > low)
low++;
array[high] = array[low];
}
array[low] = key;
return low;
}
public static int quickSort(int[] arr, int low, int high, int k) {
if (low > high) {
return -1;
}
int index = sort(arr, low, high);
if (index == k - 1) {
return arr[index];
} else if (index < k - 1) {
return quickSort(arr, index + 1, high, k);
} else if (index > k - 1) {
return quickSort(arr, low, index - 1, k);
}
return -1;
}
public static void main(String[] args) {
int[] arr={3,1,2,5,4,7,6};
System.out.print(quickSort(arr,0,arr.length-1,2));
}
}