【heapSort】
来源:互联网 发布:自控软件 编辑:程序博客网 时间:2024/06/06 10:07
链接:http://blog.csdn.net/touch_2011/article/details/6767673
第一步:建堆,形成大(小)根堆;
第二步:将堆顶与最后一个交换,并调整根堆;
第三步:重复第二步,直到结束;
时间复杂度O(nlogn) 适合数据量较大的排序,效果明显;
#include<iostream>using namespace std;void MaxHeap(int *a,int i,int n){ int left,right,largest,least; left=largest=least=2*i; if(left>n) return; right=2*i+1; //将最大的放在最后,即:形成正序; if(right<=n && a[left]<a[right]) largest=right; if(a[i]<a[largest]){ swap(a[i],a[largest]); MaxHeap(a,largest,n); // 自上向下; } /* 将最小的放在最后,即:形成倒序; if(right<=n && a[left]>a[right]) least=right; if(a[i]>a[least]){ swap(a[i],a[least]); MaxHeap(a,least,n); } */}void CreatHeap(int *a,int n){ for(int i=n/2;i>=1;i--) // 自下向上;调整为根堆形式(子根堆也满足); MaxHeap(a,i,n);}void HeapSort(int *a,int n){ CreatHeap(a,n); // 依次用堆顶值和最后一个交换;相当于选择排序; for(int i=n;i>=2;i--){ a[1]=a[1]+a[i]; a[i]=a[1]-a[i]; a[1]=a[1]-a[i]; // swap(a[1],a[i]); MaxHeap(a,1,i-1); }}int main(){ int a[]={0,9,8,7,6,5,4,3,2,1}; // 从下标为1开始排序; HeapSort(a,9); for(int i=1;i<=9;i++) cout<<a[i]<<' '; cout<<endl; return 0;}
0 0
- Heapsort
- Heapsort
- HeapSort
- heapsort
- HeapSort
- HeapSort
- HeapSort
- heapsort
- heapsort
- heapsort
- HeapSort
- Heapsort
- HeapSort
- heapSort
- HeapSort
- heapSort
- HeapSort
- heapsort
- android中定制自己的日志打印工具
- iOS 判断字符串"<null>"类型
- Extjs学习笔记(四) 数据代理
- java语言:方法重载&方法重写&继承
- 解决 类似 sdk\build-tools\23.0.1\aapt.exe'' finished with non-zero exit value 1 这种问题
- 【heapSort】
- #HDU 2647 Reward 【拓扑排序】
- NuGet学习笔记(1)——初识NuGet及快速安装使用
- F5负载均衡器的问题荟萃
- 【opencv】win7 64位系统 opencv1.0与vc6.0配置|opencv2.4.9与vs2012配置
- 关于SDL多指触屏事件获取各手指状态的问题。
- 主键、自增主键、主键索引、唯一索引概念区别与性能区别
- Android 中图片的格式
- ubuntu 终端命令