建最小堆min_heap_sort
来源:互联网 发布:php支持多继承吗 编辑:程序博客网 时间:2024/06/06 03:09
建最小堆与最大堆方法相同 只要改动max_heapify()函数里的判断条件即可.
#include<iostream>
using namespace std;int Parent(int i)
{
return i/2;
}
int Left(int i)
{
return 2*i;
}
int Right(int i)
{
return 2*i+1;
}
void exchange(int *a,int *b)
{
int t=*a;
*a=*b;
*b=t;
}
void min_heapify(int *a,int i,int heap_size)
{
int l=Left(i);
int r=Right(i);
int smallest;
if(l<=heap_size&&a[l]<a[i])//改动
smallest=l;
else
smallest=i;
if(r<=heap_size&&a[r]<a[smallest]) ///改动
smallest=r;
if(smallest!=i)
{
exchange(&a[smallest],&a[i]);
min_heapify(a,smallest,heap_size);
}
}
void Build_min_heap(int *a,int length)
{
int heap_size=length;
for(int i=length/2;i>0;--i)
min_heapify(a,i,heap_size);
}
void output(int *a,int size)
{
for(int i=0;i<size;++i)
cout<<a[i]<<" ";
cout<<endl;
}
void Heap_Sort(int *a,int size)
{
Build_min_heap(a,size);
for(int i=size;i>1;--i)
{
exchange(&a[i],&a[1]);
--size;
min_heapify(a,1,size);
}
}
int main()
{
int a[11]={2222,4,1,3,2,16,9,10,14,8,7};
Build_min_heap(a,10);
output(a+1,10);
Heap_Sort(a,10);
output(a+1,10);
return 0;
}
0 0
- 建最小堆min_heap_sort
- Python建最小堆
- PAT12-012【建最小堆】
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最小堆
- 最大堆/最小堆
- 最小堆。最大堆。
- 高校云平台(十):Jboss远程访问流程总结
- 学习的感想
- 1017. Queueing at Bank 解析
- Problem A. Vote Google APAC 2017 University Test Round D
- [BZOJ3688]折线统计(dp+bit优化)
- 建最小堆min_heap_sort
- 【Python】list数组赋值
- 《javascript高级程序设计》总结(一):javascript介绍
- Python简单爬虫导出CSV文件
- Educational Codeforces Round 17-C Two strings
- 关于平衡树(Splay)的一些总结
- 3.8 平均数
- jquery eval解析JSON中的注意点介绍
- vi编辑器替换命令:n1,n2s/word1/word2/g结尾g的作用