思路:构造大顶堆,将堆顶元素和最后一个元素交换,从新调整大顶堆,重复此过程完成排序。
节点i的父节点为: (i-1)/2;
节点i的左子树为:i*2+1;
节点i的右子树为:i*2+2;
调整大顶堆时注意要从最后一课子树从下向上调整
public static void heapsort(int[] a){
int i;
for(i=a.length/2-1;i>=0;i--){
//从最后一课子树开始调整为大顶堆
adjustHeap(a,i,a.length-1);
}
for(i=a.length-1;i>=0;i--){
//将堆顶元素和最后一位交换,并且从新调整大顶堆
int temp = a[0];
a[0] = a[i];
a[i] = temp;
adjustHeap(a,0,i-1);
}
}
public static void adjustHeap(int[] a,int index,int heapSize){
//index 子树的根节点 heapSize需要调整的堆大小
int left = index*2+1;
int right = index*2+2;
int largest = index;
if(left<heapSize&&a[left]>a[index]){
largest = left;
}
if(right<heapSize&&a[right]>a[largest]){
largest = right;
}
if(largest!=index){
int temp = a[index];
a[index] = a[largest];
a[largest] = temp;
adjustHeap(a, largest, heapSize);
}
}