内部排序算法之堆排序
2014-04-01 17:12
155 查看
堆排序是利用堆的性质, 从缩小的排序空间中不断的选出堆顶元素,从而达到排序的效果。
堆排序的时间复杂度主要是在不断的调整堆以满足堆的性质,其评价性能和最差情况都是O(logN), 平均性能差于快速排序,但最坏情况优于快速排序。
堆可以作为具有优先级队列的实现。通常在数据量较大的时候,而需要选择出前面较大的几个元素时候, 可以考虑堆排序。
堆排序的实现分为4步:
1. 初始化堆, 这个过程就是将数组堆化。
2. 选出堆顶元素, 即用待排序空间的最后一个元素和堆顶交换
3. 缩小待排序空间,调整待排序空间,使其满足堆的性质。
4. 重复2
贴上完整代码
堆排序的时间复杂度主要是在不断的调整堆以满足堆的性质,其评价性能和最差情况都是O(logN), 平均性能差于快速排序,但最坏情况优于快速排序。
堆可以作为具有优先级队列的实现。通常在数据量较大的时候,而需要选择出前面较大的几个元素时候, 可以考虑堆排序。
堆排序的实现分为4步:
1. 初始化堆, 这个过程就是将数组堆化。
2. 选出堆顶元素, 即用待排序空间的最后一个元素和堆顶交换
3. 缩小待排序空间,调整待排序空间,使其满足堆的性质。
4. 重复2
贴上完整代码
#include <stdio.h> #include <stdlib.h> #include <time.h> #define SIZE 10 #define swap(x, y) do { \ *(x) ^= *(y); \ *(y) ^= *(x); \ *(x) ^= *(y); \ }while(0); int heap_sort(int*p, int n); int heap_adjust(int*p, int i, int n); int gen_random(int*p, int n); void show(int*p, int n); int main() { int p[SIZE]; gen_random(p, SIZE); show(p, SIZE); heap_sort(p, SIZE); show(p, SIZE); } int gen_random(int*p, int n) { if(NULL == p) { printf("Error: Null pointer\n"); return -1; } if(n <= 0) { printf("Error: Invalid length\n"); return -1; } srand(time(NULL)); while(n>0) { p[--n] = rand()%1000; } return 0; } void show(int*p, int n) { int i = 0; while(i<n) { printf("%-4d", p[i++]); } printf("\n"); } int heap_sort(int*p, int n) { int i; // build heap, adjust the not-leaf node for(i=n/2-1; i>=0; --i) { heap_adjust(p, i, n); } // select the item for(i=n-1; i>=1; --i) { swap(p, p+i); heap_adjust(p, 0, i); } } int heap_adjust(int*p, int i, int n) { int child, temp; for( ; 2*i+1 < n; i = child) { child = 2 * i + 1; if( child + 1 < n && p[child + 1] > p[child]) { ++child; } if(p[i] < p[child]) { swap(p+i, p+child); } } }
相关文章推荐
- 【数据结构与算法】内部排序之三:堆排序(含完整源码)
- 【数据结构与算法】内部排序之三:堆排序(含完整源码)
- 【数据结构与算法】内部排序之三:堆排序(含完整源码)
- 【数据结构与算法】内部排序之三:堆排序(含完整源码)
- 【数据结构与算法】内部排序之三:堆排序(含完整源码)
- 【数据结构与算法】内部排序之三:堆排序(含完整源码)
- 算法和数据结构---排序---堆排序
- 【数据结构和算法】排序算法之二:选择排序和堆排序
- 选择排序、快速排序、希尔排序、堆排序不是稳定的排序算法, 冒泡排序、插入排序、归并排序和基数排序是稳定的排序算法。
- 小范围排序(巧用堆排序) -- 算法小结
- 内部排序算法相关优化及总结(二)
- 【数据结构与算法】内部排序之五:计数排序、基数排序和桶排序(含完整源码)
- 【更新】排序算法比较:插入排序,冒泡排序,归并排序,堆排序,快速排序,计数排序,基数排序,桶排序
- 内部排序之堆排序
- 算法分析-选择排序(直接选择排序 & 堆排序)
- 算法与数据结构——排序(六)堆排序
- 算法 ----- 排序NB二人组 堆排序 归并排序
- 经典内部排序: 堆排序,快排,归并排序
- 【数据结构与算法】内部排序之四:归并排序和快速排序(含完整源码)
- 算法导论之插入排序,选择排序,归并排序,冒泡排序,希尔排序,堆排序,快速排序的c语言实现