思路:
始終維持一個K個元素的最小堆,對輸入的前K個元素端三,先構成一個K個元素的最小堆舷礼,然后對后面輸入的每個元素,先和堆頂a[0]比較郊闯,若小于等于a[0]妻献,則不做處理,否則团赁,將當前輸入的元素賦值給a[0]育拨,然后將其下浮到合適的位置。
import java.util.ArrayList;
import java.util.Arrays;
public class zuidadui {
public static void main(String[] args){
int aim[] = {1, 2, 5, 10, 3, 7, 11, 15, 17, 20, 9, 15, 8, 16};
int len = aim.length;
int haipa[] = new int[len],q=0;
for(int p:aim){
haipa[q++] = (-1)*p;
}
int K = 5;
Arrays.sort(haipa);
Show(haipa);
build_min_dui(aim,K); //通過上浮的方法構建K個元素的最小堆
Show(aim);
for(int j = K;j<len;j++) { //對從 K+1 到元素末尾 欢摄,插入最小堆
//若要插入的元素比堆頂元素小或相等熬丧,則不處理,否則將其付給堆頂元素怀挠,并將其下沉到合適位置析蝴。
if(aim[j] > aim[0]){
down(aim, K, j);
}
}
Show(aim);
}
public static void build_min_dui(int a[],int K){
for(int i = 1;i< K;i++){
up_floor(a, i);
}
}
public static void down(int a[],int K,int cur) {
a[0] = a[cur];
cur = 0;
while(cur < K){
int child = 2*cur + 1;
if(child >= K)break;
else{
if(child < K -1 && a[child] >a[child +1]){
child++;
}
if(a[cur]>a[child]){
int tempt = a[child];
a[child] = a[cur];
a[cur] = tempt;
cur = child;
}else
break;
}
}
}
public static void up_floor(int a[],int flag){
int tt;
if(flag > 0){
int par = (flag - 1)/2;
if(a[par] > a[flag]) {
tt = a[flag];
a[flag] = a[par];
a[par] = tt;
up_floor(a, par);
}
}
}
public static void Show(int a[]){
for(int i : a){
System.out.print(i + " ");
}
System.out.println();
}
}