实现代码
public class Heap {public static void main(String[] args) {int arr[] = {1,0,3,2,6,5,4,9};for(int i=arr.length/2-1;i>=0;i--) {adjust(arr,i,arr.length-1);}System.out.println("调整堆结果");for(int i=0;i<arr.length;i++) {System.out.print(arr[i]+" ");}System.out.println();int heapArr[] = {1,0,7,3,8,2,10,6,5,4,9};sort(heapArr,heapArr.length-1);System.out.println("排序结果");for(int i=0;i<heapArr.length;i++) {System.out.print(heapArr[i]+" ");}}public static void adjust(int heapArr[],int fatherNode,int endIndex) {int temp;if(fatherNode*2+1>endIndex)return;if(fatherNode*2+1==endIndex) {if(heapArr[fatherNode*2+1]>heapArr[fatherNode]) {temp = heapArr[fatherNode];heapArr[fatherNode] = heapArr[fatherNode*2+1];heapArr[fatherNode*2+1] = temp;}return;}if(fatherNode*2+1<endIndex) {if(heapArr[fatherNode*2+1]>heapArr[fatherNode]) {temp = heapArr[fatherNode];heapArr[fatherNode] = heapArr[fatherNode*2+1];heapArr[fatherNode*2+1] = temp;}if(heapArr[fatherNode*2+2]>heapArr[fatherNode]) {temp = heapArr[fatherNode];heapArr[fatherNode] = heapArr[fatherNode*2+2];heapArr[fatherNode*2+2] = temp;}adjust(heapArr, fatherNode*2+1, endIndex);adjust(heapArr, fatherNode*2+2, endIndex);}}public static void sort(int heapArr[],int endIndex) {if(endIndex<0)return;for(int i=(endIndex+1)/2-1;i>=0;i--) {adjust(heapArr,i,endIndex);}int temp;temp = heapArr[0];heapArr[0] = heapArr[endIndex];heapArr[endIndex] = temp;sort(heapArr, endIndex-1);}}
测试结果