标签:
//堆排序C++实现 #include<iostream> #include<functional> using namespace std; void HeapSort(int* arr, int cnt) { function<void(int*, int, int)> percdown = [&](int* arr, int i, int cnt) //下滤操作 { int child = 0, tmp = 0; for (tmp = arr[i]; 2 * i + 1 < cnt; i = child) { child = i * 2 + 1; if (child != cnt - 1 && arr[child + 1] > arr[child]) child++; if (tmp < arr[child]) arr[i] = arr[child]; else break; } arr[i] = tmp; }; for (int i = (cnt-1) / 2; i >= 0; i--) //从最后一个元素的父节点开始一个一个的下滤,构建堆 注意:这里的i = cnt 或 cnt -1 均可,可以自行画图解释 percdown(arr, i, cnt); for (int i = cnt - 1; i > 0; i--) //把构建好的堆进行排序 { swap(arr[0], arr[i]); percdown(arr, 0, i); } } int main() { const int cnt = 1159; int arr[cnt]; int tmp = -1; for (int i = 0; i < cnt; i++) { if (i % 2) arr[i] = i; else arr[i] = i * tmp; } HeapSort(arr, cnt); for (auto i : arr) cout << i << endl; for (int i = 0; i < cnt-1; i++) { if (arr[i] > arr[i + 1]) cout << "haha" << endl; } cout << "test end" << endl; cin.get(); return 0; }
标签:
原文地址:http://blog.csdn.net/linukey/article/details/46476755