问题:有一个大小为n的数组A[0,1,2,…,n-1],求其中第k大的数。
使用类似排序的方法,执行一次排序后,每次只选择一部份继续快排,直到找到第K大元素为止。时间复杂度是O(n)
package test.cn;
public class sdsd {
public static int partition(int[] arr,int low,int high){
int temp=arr[low];
while(low<high){
while(arr[high]<=temp&&high>low)
--high;
arr[low]=arr[high];
while(arr[low]>=temp&&low<high)
++low;
arr[high]=arr[low];
}
arr[high]=temp;
return high;
}
public static void find_k(int k,int[] arr,int low,int high){
int temp=partition(arr,low,high);
if(temp==k-1){
System.out.print("第"+k+"大的数是:"+arr[temp]);
}else if(temp>k-1){
find_k(k,arr,low,temp-1);
}else{
find_k(k,arr,temp+1,high);
}
}
public static void main(String[] args) {
int[] arr={3,1,2,5,4,7,6};
find_k(6,arr,0,arr.length-1);
}
}