#include <iostream>
using namespace std;
void maxsort(int tree[],int n,int i)
{
int l = 2*i+1;
int r = 2*i+2;
int max = i;
if(l<n&&tree[l]>tree[i])
{
max = l;
swap(tree[l],tree[i]);
}
if(r<n&&tree[r]>tree[i])
{
max = r;
swap(tree[r],tree[i]);
}
if(max != i)
{
maxsort(tree,n,max);
}
}
void build_sort(int tree[],int n)
{
int nodelen = n-1;
for(int i=nodelen-1;i>=0;i--) //从最后一个子树到第一个子树
{
maxsort(tree, n, i);
}
}
void heap_sort(int tree[],int n)
{
build_sort(tree, n);
for(int i=n-1; i>=0; i--)
{
swap(tree[0],tree[i]);
maxsort(tree,i,0);
}
}
int main()
{
int tree[] = {9,100,2,60};
int len = sizeof(tree)/sizeof(tree[0]);
heap_sort(tree,len);
for(int i=0;i<len;i++)
{
cout<<tree[i]<<endl;
}
return 0;
}
使用C++实现最小堆排序
最新推荐文章于 2022-01-21 16:40:54 发布