堆排序
2015-08-31 21:18
169 查看
一、概念
堆排序是利用堆这种数据结构的性质设计的一种排序方式。
堆是一个近似完全二叉树的结构,并满足性质:子节点的键值或则索引值总是小于等于(或则大于等于)父节点的。
是不稳定排序。
二、原理
1.首先将待排序的数组进行堆化,构建成堆结构
2.将堆首和堆尾进行交换
3.将堆大小减一,并调整剩下的数据,将数组顶端数据调整到合适的位置,保证依然保证是堆的结构
4.重复2、3,直到大小为1,此时数据已经有序
三、复杂度
时间复杂度:O(nlog(n))
空间复杂度:O(1)
四、原理图
五、代码实现
堆排序是利用堆这种数据结构的性质设计的一种排序方式。
堆是一个近似完全二叉树的结构,并满足性质:子节点的键值或则索引值总是小于等于(或则大于等于)父节点的。
是不稳定排序。
二、原理
1.首先将待排序的数组进行堆化,构建成堆结构
2.将堆首和堆尾进行交换
3.将堆大小减一,并调整剩下的数据,将数组顶端数据调整到合适的位置,保证依然保证是堆的结构
4.重复2、3,直到大小为1,此时数据已经有序
三、复杂度
时间复杂度:O(nlog(n))
空间复杂度:O(1)
四、原理图
五、代码实现
//从root位置开始向下调整,数组长度为size void heap_adjust(int arr[], int root, int size) { int left_child; int key; key = arr[root]; left_child = 2 * root + 1; while (left_child < size) { if ((left_child + 1 < size) && (arr[left_child + 1] > arr[left_child])) { left_child++; } if (arr[left_child] <= key) { break; } arr[root] = arr[left_child]; root = left_child; left_child = 2 * root + 1; } arr[root] = key; } //将待排序数组进行堆化 void build_heap(int arr[], int size) { int index; for (index = size / 2; index >= 0; index--) { heap_adjust(arr, index, size); } } //用于交换两个数(用异或只适用整数) void swap(int *x, int *y) { *x = *x ^ *y; *y = *x ^ *y; *x = *x ^ *y; } //堆排序主函数 void heap_sort(int arr[], int size) { int index; build_heap(arr, size); for (index = size - 1; index >= 1; index--) { swap(&arr[0], &arr[index]); heap_adjust(arr, 0, index); } }
相关文章推荐
- 异常“未能加载文件或程序集"DAL"或它的某一个依赖项。系统找不到指定的文件。”的解决办法
- 4Sum(****) 基于3Sum
- 国外整理的一套在线渗透测试资源合集
- Tiny_4412的NFS挂载
- xampp和testlink的安装
- Android-调用本地方法将小写字符串转成大写字符串/NDK-JNI开发实例(四)
- 惠普实训生活记录-1
- Canvas做股票数据走势图实践分享(一)
- HTML简介
- 使用NSURLConnection实现断点续传。
- 对惠普实训的感想
- 面试10大算法汇总+常见题目解答
- iOS-UI基础-02加法计算器
- BI 面试 题
- LIBSVM使用手册与机器学习中几个常见观点
- 8月31日,即将迎来大学生活。以此记录我的编程博客之旅。
- 网络编程
- 一个死锁程序
- 模板函数和模板类的区别
- iOS开发 ----- UI生命周期