public class Main {
static int heapLen;//堆的大小
static int[] heapList= {0,5,4,7,1,3};//堆数组的第一个位置不放元素;
//judge函数,找出父节点与两个子节点的中最大的,并返回最大元素的下标
public static int judge(int pos){
if(2*pos>heapLen){
return pos;
}else if(2*pos+1>heapLen){
if(heapList[pos]<heapList[2*pos]){
return 2*pos;
}else{
return pos;
}
}else{
if((heapList[pos]>=heapList[2*pos])&&(heapList[pos]>=heapList[2*pos+1])){
return pos;
}else{
if(heapList[2*pos]>=heapList[2*pos+1]){
return 2*pos;
}else{
return 2*pos+1;
}
}
}
}
//输入一个下标,从这个下标开始调整堆。
public static void adjustHeap(int pos){
while(judge(pos)!=pos){
int temp;
int p =judge(pos);
temp = heapList[pos];
heapList[pos] = heapList[p];
heapList[p] = temp;
pos = judge(pos);
}
}
//创建堆
public static void creatHeap(){
for(int i=heapLen/2;i>=1;i--){
adjustHeap(i);
}
}
//删除堆首元素
public static void deleteHeap(){
//交换首尾元素
int temp;
temp = heapList[1];
heapList[1] = heapList[heapLen];
heapList[heapLen] = temp;
heapLen--;
adjustHeap(1);
}
//输出堆
public static void printList(){
for (int i=1;i<=heapList.length-1;i++){
System.out.print(heapList[i]+" ");
}
System.out.println();
}
public static void main(String[] args){
heapLen = heapList.length-1;
creatHeap();
for (int i=1;i<heapList.length-1;i++){
deleteHeap();
}
printList();
}
}