算法思想见算法导论,这里是我的具体C++实现,代码可直接编译运行。
#include <iostream> using namespace std; void heapfy(int a[], int start, int end) { int large = start; int i = start; int swap_tmp = 0; while (i < end) { if (2*i+1 < end) { if (a[2*i+1] > a[large]) { large = 2*i+1; } } if (2*i+2 < end) { if (a[2*i+2] > a[large]) { large = 2*i+2; } } if (i != large) { swap_tmp = a[i]; a[i] = a[large]; a[large] = swap_tmp; i = large; } else { break; } } } void print (int a[], int len) { for (int i = 0; i < len; i++) { cout << a[i] << " "; } cout << endl; } void build_heap(int a[], int len) { int mid = len/2 - 1; for (int i=mid; i>=0; i--) { heapfy(a, i, len); cout << i << ":"; print(a, len); } } void heap_sort (int a[], int len) { build_heap(a, len); int swap_tmp = 0; for (int i=len-1; i>=1; i--) { swap_tmp = a[0]; a[0] = a[i]; a[i] = swap_tmp; heapfy(a, 0, i); } } int main () { int a[] = {0, 9,2,13,4,5,20,11,7}; int array_size = sizeof(a)/sizeof(int); //cout << array_size << endl; //heapfy(a, 0, array_size); heap_sort(a, array_size); print(a, array_size); return 0; }