标签:
#include <iostream> using namespace std; void HeapAdjust(int* a, int start, int n) { int max=start; int lchild = start*2+1; int rchild = start*2+2; if(start <= (n-1)/2){ if(lchild <=n && a[lchild]>a[max]){ max = lchild; } if(rchild <=n && a[rchild]>a[max]){ max = rchild; } if(max!=start){ swap(a[start], a[max]); HeapAdjust(a, max, n); } } } void BuildHeap(int* a, int n){ //n: [0,n] for(int i = (n-1)/2; i >=0;i--){ HeapAdjust(a, i, n); } } void HeapSort(int *a,int n) { BuildHeap(a,n); for(int i=n;i>=0;i--) { swap(a[0],a[i]); HeapAdjust(a,0,i-1); } } int main(int argc, char *argv[]) { int a[]={6,36,77,31,181,7,8}; BuildHeap(a,6); for(int i=0;i<7;i++){ cout << a[i] <<endl; } cout << "=================" <<endl; HeapSort(a,6); for(int i=0;i<7;i++){ cout << a[i] <<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/lifeinsmile/p/5228989.html