标签:堆排序
/*堆排序*/ #include <iostream> using 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); } } void HeapSortTest() { int array[] = {1, 3, 5, 7, 9, 2, 4, 6, 8, 10}; HeapSort(array, sizeof(array)/sizeof(array[0])); for (size_t i = 0; i < sizeof(array)/sizeof(array[0]); ++i) { cout<<array[i]<<" "; } cout<<endl; } int main() { HeapSortTest(); return 0; }
本文出自 “zgw285763054” 博客,请务必保留此出处http://zgw285763054.blog.51cto.com/11591804/1785316
标签:堆排序
原文地址:http://zgw285763054.blog.51cto.com/11591804/1785316