HeapSort(堆排序算法)
来源:互联网 发布:投诉淘宝店铺投诉电话 编辑:程序博客网 时间:2024/05/21 12:24
其实说白了堆排序就是一种特殊的插入排序,只是运用了树形结构而已,使得两个数时间的比较减少了一半,时间复杂度为(n*lg(n))级别的,而且还是原址排序哟。。。
堆排序的关键是构造几个函数:
1.HeapAdjust(int *a,int i)//调整下标为i的堆的元素在堆中保持堆的性质(即父亲节点永远大于两个儿子节点———最大堆的性质,最小堆相反)
2.BuildHeap(int *a,int size)//将数组元素调整为最大堆,使其保持堆的性质
3.HeapSort(int *a,int size)//不断从堆中取出最大值然后与数组后面(这里的后面你懂得),然后堆的size减一,不断循环直至堆中所有的元素都放入数组中。
说了那么多,上代码吧。。。
#include <stdio.h>#include <algorithm>#include <iostream>using namespace std;int left(int i){ return i*2;}int right(int i){ return i*2+1;}void HeapAdjust(int *a,int i,int size){ int l=left(i); int r=right(i); int largest=i; if(i>size/2) return; if(l<=size&&a[l]>a[largest]) { largest=l; } if(r<=size&&a[r]>a[largest]) { largest=r; } if(largest!=i) { swap(a[largest],a[i]); HeapAdjust(a,largest,size); }}void BuildHeap(int *a,int size){ for(int i=size/2;i>=1;i--) { HeapAdjust(a,i,size); }}void HeapSort(int *a,int size){ BuildHeap(a,size); for(int i=size;i>=2;i--) { swap(a[i],a[1]); HeapAdjust(a,1,i-1); }}int main(){ int a[1000]; int size; while(scanf("%d",&size),size) { for(int i=1;i<=size;i++) { scanf("%d",&a[i]); } HeapSort(a,size); for(int i=1;i<=size;i++) { printf("%d ",a[i]); } puts(""); } return 0;}
1 0
- HeapSort(堆排序算法)
- 排序算法 之 堆排序(heapsort)
- Java排序算法--堆排序(HeapSort)
- 经典算法(9)- 堆排序(Heapsort)
- Java堆排序(HeapSort)算法实现
- 堆排序(HeapSort)
- 堆排序(Heapsort)
- 堆排序 (Heapsort)
- 堆排序(heapsort)
- 堆排序(HeapSort)
- 堆排序(heapsort)
- 堆排序(heapsort)
- 堆排序(Heapsort)
- 堆排序(HeapSort)
- 堆排序(Heapsort)
- 堆排序(HeapSort)
- 堆排序(heapsort)
- 堆排序(HeapSort)
- 宏countof() 得到数组长度
- Excel、脚本语言、MPP数据库到Hadoop ——MB、GB、TB到PB
- sat阅读想要短期提高做什么好?
- 算法导论16(贪心算法)
- 安卓真机调试之 INSTALL_FAILED_MEDIA_UNAVAILABLE
- HeapSort(堆排序算法)
- MFC 改变控件大小和位置
- SYN Flood攻击
- 实现简答LinkedList
- 安全之公开密钥基本知识
- miniUI Tabs 懒加载
- blocks 循环引用问题
- 图像分割—基于图的图像分割(Graph-BasedImageSegmentation)
- linux c 编程 log输出