#include <iostream> using namespace std; void Sort(int* a,int num,int n){ int c = 2 * num + 1; while(c+1 < n){ if(a[c+1] > a[c]){ c++; } if(a[c] > a[num]){ int tmp = a[c]; a[c] = a[num]; a[num] = tmp; num = c; c = 2 * num + 1; } else{ break; } } if(c+1 == n){ if(a[c]>a[num]){ int tmp = a[c]; a[c] = a[num]; a[num] = tmp; } } } void CreateHeap(int* a,int n){ int t = (n-1) / 2; //最后一个非叶子点 for(int i=t;i>=0;i--){ Sort(a,i,n); } } void HeapSort(int* a,int n){ for(int i=n-1;i>=0;i--){ int tmp = a[i]; a[i] = a[0]; a[0] = tmp; Sort(a,0,i); //因为把0和最后的元素交换,所以每次都只需要从0开始构建heap } } int main() { int a[] = {5,2,8,7,4,1,6,9,3,10}; int n = 10; CreateHeap(a,n); HeapSort(a,n); for(int i=0;i<n;i++){ cout << a[i] << " "; } return 0; }