建最小堆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
原创粉丝点击