/**
* Created by create on 2019/11/18.
*/
public class test01 {
public static void main(String [] args){
int [] m = {7,5,19,8,4,1,20,13,16};
int [] a = new int [10];
for (int j = 1; j<10 ; j++){
a[j] = m[j-1];
}
//原始数据序列
for (int i = 1; i < 10; i++) {
System.out.println(a[i]);
}
buildHeap(a,9);
//构建大顶堆后
for (int i = 1; i < 10; i++) {
System.out.println(a[i]);
}
}
private static void buildHeap(int [] a, int n){
for (int i = n/2; i>=1; --i){
heapify(a, n, i);
}
}
private static void heapify(int[] a, int n, int i){
while(true){
int maxPos = i;
if(i*2 <=n && a[i*2] > a[i]){maxPos = i*2;}
if(i*2+1 <= n && a[i*2+1] > a[maxPos]){maxPos = i*2+1;}
if(maxPos ==i) break;
swap(a, i, maxPos);
i = maxPos;
}
}
private static void swap(int [] a, int i, int maxPos){
int tmp = a[i];
a[i] = a[maxPos];
a[maxPos] = tmp;
}
}