C++实现堆排序
发表于:2024-11-27 作者:热门IT资讯网编辑
编辑最后更新 2024年11月27日,/*堆排序*/#include using namespace std;void AdjustDown(int* array, size_t size, size_t parent){
/*堆排序*/#includeusing namespace std;void AdjustDown(int* array, size_t size, size_t parent){ size_t child = parent*2 + 1; while (child < size) { if (child+1 < size && array[child] < array[child+1]) { ++child; } if (array[child] > array[parent]) { swap(array[child], array[parent]); parent = child; child = parent*2 + 1; } else { break; } }}void HeapSort(int* array, size_t size){ //建堆 for (int i = (size-2)/2; i >= 0; --i) { AdjustDown(array, size, i); } //选数据排序 for (size_t i = 0; i < size; ++i) { swap(array[0], array[size-i-1]); AdjustDown(array, size-i-1, 0); }}