public class MoreThanHalf {
/**
* 升序
* @param array
* @param start
* @param end
* @return
*/
public static int partition(int[] array, int start, int end){
int num = array[start];
int i = start;
int j = end;
while(i<j){
while(i<j&&array[j]>=num){
j--;
}
array[i] = array[j];
while(i<j&&array[i]<num){
i++;
}
array[j] = array[i];
}
array[i] = num;
return i;
}
/**
* 降
* @param array
* @param start
* @param end
* @return
*/
public static int lowpartition(int[] array, int start, int end){
int num = array[start];
int i = start;
int j = end;
while(i<j){
while(i<j&&array[j]<=num){
j--;
}
array[i] = array[j];
while(i<j&&array[i]>num){
i++;
}
array[j] = array[i];
}
array[i] = num;
return i;
}
/**
* 找最大或最小的k个数
* @param array
* @param k
*/
public static void findMorethenhalf(int[] array,int k){
int start = 0;
int end = array.length-1;
int key = lowpartition(array,start,end);
int n = array.length;
int sta = k;
while(key!=sta){
if(key>sta){
key = lowpartition(array,start,key-1);
}else{
key = lowpartition(array,key+1,end);
}
}
for(int i=0;i<sta;i++){
System.out.println(array[i]);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = {2,3,4,5,4,4,4,4,4};
findMorethenhalf(array,2);
}
}
取第k大的数
最新推荐文章于 2021-12-07 14:49:14 发布