public class Test {
public static void main(String[] args) {
//生成一个数组
int[] arrays = buildArray(30);
printArray(arrays);
getTopN(arrays,10);
printArray(arrays);
}
//向下调整,构建小顶堆的
public static void downAdjust2(int[] arrays, int parentIndex,int length) {
int temp = arrays[parentIndex];
int childIndex = 2* parentIndex + 1;
while (childIndex < length) {
if(childIndex+1< length && arrays[childIndex+1] < arrays[childIndex])
childIndex ++;
if(temp<=arrays[childIndex])
break;
arrays[parentIndex] = arrays[childIndex];
parentIndex = childIndex;
childIndex = 2 * parentIndex + 1;
}
arrays[parentIndex] = temp;
}
public static void buildHeap2(int[] arrays, int n) {
//n为数组的长度
for(int i = n/2-1;i>=0;i--) {
downAdjust2(arrays,i,n);
}
}
public static void getTopN(int[] arrays,int n) {
//首先对arrays的前n个数字,构建小顶堆
buildHeap2(arrays,n);
for(int i=n ;i<arrays.length;i++) {
//如果第i个数字小于堆顶,则继续循环,否则将其替换为堆顶元素,然后进行向下调整
if(arrays[i] < arrays[0]) {
continue;
} else {
//这里可以不用交换,直接arrays[0]=arrays[i]就行。
//进行交换的目的是为了得到的答案看起来更清晰一些
int temp = arrays[0];
arrays[0] = arrays[i];
arrays[i]=temp;
downAdjust2(arrays,0,n);
}
}
}
public static int[] buildArray(int n) {
int[] arrays = new int[n];
for(int i = 0;i<n;i++) {
arrays[i] = i;
}
return arrays;
}
public static void printArray(int[] arrays) {
System.out.println(Arrays.toString(arrays));
}
}