#include<iostream> using namespace std; void display(int *a, int size){ for(int i = 0 ; i < size; i++){ cout << a[i] << " "; } cout << endl; } void heapSort(int *a, int i, int size){ int lc = 2*i,rc = 2*i+1,max = i; if(lc <= size && a[max-1] < a[lc-1]){ max = lc; } if(rc <= size && a[max-1] < a[rc-1]){ max = rc; } if(max != i){ swap(a[i-1],a[max-1]); if(2*max <= size){ heapSort(a,max,size); } } } void buildHeap(int *a, int size){ for(int i = size/2;i > 0; i-- ){ heapSort(a,i,size); } } int main(){ int a[] = {16,7,3,20,17,8}; int size = 6; buildHeap(a,size); swap(a[0],a[size]); size--; while(size>1){ heapSort(a,1,size); swap(a[0],a[size]); size--; } // while(--size>0){ // swap(a[0],a[size]); // heapSort(a,1,size); // } display(a,6); return 0; }
注释部分对上面的优化。
时间: 2024-10-11 07:36:25