堆排序
来源:互联网 发布:优化探究化学 编辑:程序博客网 时间:2024/06/18 00:28
今天研究学习了下数据结构中的堆排序算法,据此自己写了一个完整的算法来实践下。
//The beginning index of arrary is 0, not 1.int raw_arr[10] = {4,2,3,6,7,3,1,9,10,8};void sift(int* r, int l, int m){ int i,j; i = l; //i is the start node to keep heap j = 2 * i + 1; //j is left subnode, j+1 is right subnode //m is the size of current heap while (j < m) { //if r[i] has right subnode, then compare it with left subnode. if (j + 1 < m && r[j] < r[j+1]) j = j+1; if (r[i] < r[j]) { int tmp = r[i]; r[i] = r[j]; r[j] = tmp; i = j; j = 2*i + 1; } else { break; //if r[i] is not less than it's left and right subnodes, then break; } }}void heapsort(int* array, int n){ int i; //build heap, start from array index n/2 -1 to 0 for (i = n/2 - 1; i >= 0; i--) { sift(array, i, n); } //sort, heapsize reduce from n to 2 for (i = n; i >= 2; i--) { //exchange the maximum value array[0] with the last element in current heap int m = array[i - 1]; array[i - 1] = array[0]; array[0] = m; //after exchange, heapsize reudce 1 and keep new heap whose headsize is i - 1 if (2 > i-1) break; //it's not necessary to keep heap when heapsize is less than 2 sift(array, 0, i-1); //heapsize is i - 1 }}
0 0
- 堆及堆排序
- 堆/堆排序特点
- 【二叉堆、堆排序】
- 二叉堆 & 堆排序
- 二叉堆 & 堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆与堆排序
- 堆和堆排序
- 堆排序(最大堆)
- 堆和堆排序
- 堆和堆排序
- 堆及堆排序
- 堆和堆排序
- 堆与堆排序
- 【BASH】bash shell的使用实例
- 返璞归真 asp.net mvc (2) - 路由(System.Web.Routing)
- 我的WiFi,我的焦虑人生
- mvn eclipse eclipse required goal not found
- mysql 更改数据库文件位置
- 堆排序
- JavaWeb的各种中文乱码终极解决方法!!
- Cocos2D-X弹出对话框的实现与封装
- Mysql错误:Ignoring query to other database解决方法
- 如何解压RPM包
- HTTP头信息及响应码
- 常用的自定义UI组件- 一:TimeView
- Linux编程细节3-内核-数据结构
- linux硬链接与软链接