1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| void BuildMaxHeap(int A[], int len){ for(int i=len/2; i>0; i--) HeadAdjust(A, i, len); }
void HeadAdjust(int A[], int k, int len){ A[0] = A[k]; for(int i=2*k; i<=len; i*=2){ if(i<len && A[i]<A[i+1]) i++; if(A[0] >= A[i]) break; else{ A[k] = A[i]; k=i; } } A[k] = A[0] }
void swap(int &a, int &b){ int temp = a; a = b; b = temp; }
void HeapSort(int A[], int len){ BuildMaxHeap(A, len); for(int i=len; i>1; i--){ swap(A[i], A[1]); HeadAdjust(A,1,i-1); } }
|