堆排序

 

 1 //大顶堆调整O(log n)
 2 void maxHeapify(int A[],int heapSize,int i){
 3     int lChild=2*i;
 4     int rChild=2*i+1;
 5     int largest=i;
 6     if(lChild<=heapSize&&A[lChild]>A[largest])
 7         largest=lChild;
 8     if(rChild<=heapSize&&A[rChild]>A[largest])
 9         largest=rChild;
10     if(largest!=i){
11         swap(A[largest],A[i]);
12         maxHeapify(A,heapSize,largest);
13     }
14 }
15 //建堆O(n)
16 void buildMaxHeap(int A[],int heapSize){
17     for(int i=heapSize/2;i>=1;i--)
18         maxHeapify(A,heapSize,i);
19 }
20 //堆排序O(n log n)
21 void heapSort(int A[],int heapSize){
22     buildMaxHeap(A,heapSize);
23     for(int i=heapSize;i>=2;i--){
24         swap(A[1],A[i]);
25         heapSize--;
26         maxHeapify(A,heapSize,1);
27     }
28 }

 

posted @ 2014-09-10 15:41  liuzhiminxd  阅读(100)  评论(0编辑  收藏  举报