根据算法导论书中对对堆排序的讲解,一下代码为java实现
/*
* 该类是用来实现最大堆的*/
public class Heap {
public static void main(String []args){
int []AA =new int[] {4,1,3,2,16,9,10,14,8,7};
buildHeap(AA);
System.out.print("建立堆:");
for(int i = 0; i < AA.length; i++)
System.out.print(AA[i]+" ");
System.out.println();System.out.print("堆排序:");
sortHeap(AA,AA.length-1);
for(int i = 0; i < AA.length; i++)
System.out.print(AA[i]+" ");
}
/**
*为了使A[i]和其子节点都满足最大顿的性质
* @param A
* @param i
*/
public static void maxHeapify(int []A,int i,int heapSize){
if(i>(heapSize-1)/2)return;
int large = i;
if( i*2+1<=heapSize&&A[i]<A[i*2+1])large =(i*2+1);
if((2+i*2)<=heapSize && A[large]<A[2+i*2])
large=2+i*2;
if(large!=i){
int temp = A[large];
A[large] = A[i];
A[i] = temp;
maxHeapify(A,large,heapSize);
}
}
public static void buildHeap(int []A){
int n = A.length-1;
for(int i = (n-1)/2;i>=0;i--){
maxHeapify(A,i,n);
}
}
public static void sortHeap(int []A,int heapSize){
if(heapSize<1)return;
int temp = A[heapSize];
A[heapSize] = A[0];
A[0] = temp;
heapSize--;
maxHeapify(A,0,heapSize);
sortHeap(A,heapSize);
}
}