堆排序(C++)
2015-01-09 17:19
239 查看
建立一个小顶堆;
建立时保证左子树右子树大于根节点;
去掉堆顶;
然后把最后一项放在堆顶,然后再调整保证左子树右子树大于根节点;
再去掉堆顶;
以此类推;
建立时保证左子树右子树大于根节点;
去掉堆顶;
然后把最后一项放在堆顶,然后再调整保证左子树右子树大于根节点;
再去掉堆顶;
以此类推;
#include <iostream> using namespace std; int main() { int n; cout << "请输入数组长度:" << endl; cin >> n; int *NUM = new int ; cout << "请输入" << n << "个元素" << endl; for (int i = 0; i < n; i++) { int j = i, temp; cin >> NUM[i]; while (j > 0) { if (NUM[((j - 1) / 2)] > NUM[j]) { temp = NUM[(j - 1) / 2]; NUM[(j - 1) / 2] = NUM[j]; NUM[j] = temp; } j = (j - 1) / 2; } } while (n > 0) { int temp, tt; cout << NUM[0] << endl; NUM[0] = NUM[n - 1]; n--; temp = 0; while (((2 * temp + 1) < n) && ((2 * temp + 1) < n)) { if ((NUM[temp] <= NUM[temp * 2 + 1]) && (NUM[temp] <= NUM[temp * 2 + 2])) { break; } else { if (NUM[temp * 2 + 1] < NUM[temp * 2 + 2]) { tt = NUM[temp]; NUM[temp] = NUM[temp * 2 + 1]; NUM[temp * 2 + 1] = tt; temp = temp * 2 + 1; } else { tt = NUM[temp]; NUM[temp] = NUM[temp * 2 + 2]; NUM[temp * 2 + 2] = tt; temp = temp * 2 + 2; } } } } delete[]NUM; return 0; }
相关文章推荐
- 215题——Kth Largest Element in an Array(堆排序)
- 浅谈算法和数据结构: 五 优先级队列与堆排序
- 堆排序(递归)
- POJ2833The Average【堆排序】
- 堆排序
- 【数据结构学习】-堆与堆排序
- 堆的插入、删除和建立操作,堆排序
- java实现堆排序
- Java实现堆排序
- 堆排序
- 最小堆排序
- 数据结构之排序(五)堆排序
- 算法-排序-选择排序(直接选择和堆排序)
- 堆排序
- 不稳定排序之选择、快速、希尔以及堆排序
- 小白学算法2.7——堆排序
- 第十六周上机实践项目1 - 验证算法(堆排序)
- 第16周 项目1-堆排序
- 堆排序
- 数据结构上机实验-希尔排序,快速排序,堆排序