//heap sort
//堆排序能够分为两个过程。其一是建堆。其二是出堆 //堆是一种全然二叉树,所以它能够用数组进行存储。
//堆可分为最大堆和最小堆。最大堆指任一节点的值都大于其左右孩子节点的值,最小堆自不必说。 //STL中有一套完整的堆排序算法,其相关函数包含make_heap\push_heap\pop_heap\sort-heap
//四个函数都是接受一对迭代器作为參数。其作用分别例如以下:
//push_heap是将新值放入到最后一个迭代器的位置后,进行堆调整;
//pop_heap是将当前堆的最大值放到最后一个迭代器位置,然后进行堆调整;
//make_heap是建堆过程
//sort_heap是堆排序过程
//堆排序须要对迭代器进行大小比較及相减等工作,所以两个迭代器必须是随机存取迭代器;
//priority_queue即是以堆排序为基础的配接器容器。其底层默认以vector实现 #include<vector>
#include<iostream> using namespace std; template<class type>
void heapAdjust(vector<type>& vec,int index,int length)
{//堆排序的核心算法:堆调整
int i=index;
int j=2*i; for(;j<=length;j=j*2)
{
if(j+1<=length && vec[j]<vec[j+1])
j++;//使j指向较大值
if(vec[i]>vec[j])
break;
else
{//使较大值上浮
type tmp=vec[i];
vec[i]=vec[j];
vec[j]=tmp;
i=j;
}
}
} template<class type>
void heapSort(vector<type>& vec)
{
int length=vec.size();
for(int i=(length-1)>>1;i>=1;--i)
{//建堆的过程是一个上浮的过程,从底层逐层上浮
heapAdjust(vec,i,length-1);
} for(int i=length-1;i>1;--i)
{//出堆过程是一个下沉的过程,从堆底一直沉究竟部
type tmp=vec[1];
vec[1]=vec[i];
vec[i]=tmp;
heapAdjust(vec,1,i-1);
}
} int main()
{
int a[11]={0,1,4,8,5,9,6,3,0,2,7};
vector<int> vec(a,a+11); heapSort(vec); for(int i=1;i<vec.size();++i)
{
cout<<vec[i]<<" ";
}
cout<<endl; return 0;
}

最新文章

  1. ThinkPHP 3.2.3 Widget 扩展的使用
  2. sp.net2.0中的新增控件BulletedList的一些高级用法
  3. 【转】MYSQL入门学习之四:MYSQL的数据类型
  4. Android 图像压缩,和LRU算法使用的推荐链接
  5. Hello Bolg!
  6. Delphi中的Rtti函数
  7. FZU 1920 Left Mouse Button 简单搜索
  8. ML笔记:Where does the error come from?
  9. 从Myeclipse到Intelj Idea
  10. 安装anaconda和python3.7环境
  11. [转]一千行 MySQL 学习笔记
  12. Scrapy爬虫(4)爬取豆瓣电影Top250图片
  13. Nginx proxy_protocol协议
  14. python wmi模块 获取windows内部信息
  15. 2017-5-19&amp;5-23/系统性能指标
  16. 小程序 wepy wx.createAnimation 向右滑动渐入渐出
  17. 洛谷P4486 Kakuro
  18. ZooKeeper(二)Java API使用
  19. Maven仓库 - 分发构件至远程仓库
  20. [C#] == VS Equals

热门文章

  1. 13. OPTIMIZER_TRACE
  2. kvm安装图终端界面及形界面安装系统
  3. timeslot概念(还是不太懂呀!!)
  4. python-基本运算符(解压缩-必考)
  5. 【HIHOCODER 1469 】福字(DP)
  6. Hyperledger Fabric创建通道抛错Error: got unexpected status: FORBIDDEN -- Failed to reach implicit threshold of 1 sub-policies, required 1 remaining: permission denied解决方案
  7. xtu summer individual 1 A - An interesting mobile game
  8. Python 和 Flask实现RESTful services
  9. NYOJ-183赚钱啦,bellman//spfa水过,,题还是蛮变态的赶脚~~
  10. python去掉BOM头的方法