要求:用一维数组建堆,然后堆排序。
输入:10
1 3 4 6 5 2 10 8 9 7
输出:1 2 3 4 5 6 7 8 9 10
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int da[100];
bool cmp(int a,int b){return a<b;}
void heapadjust(int s[],int i,int size,bool compare(int,int))
{
int lchild=i<<1;
int rchild=i<<1|1;
int mmax=i;
if(i<=size/2)
{
if(lchild<=size&&compare(s[mmax],s[lchild]))mmax=lchild;
if(rchild<=size&&compare(s[mmax],s[rchild]))mmax=rchild;
if(mmax!=i)
{
swap(s[i],s[mmax]);
heapadjust(s,mmax,size,compare);
}
}
}
void heapsort(int *s,int size,bool compare(int,int))//堆排序
{
s--;
for(int i=size/2;i>=1;i--)
heapadjust(s,i,size,compare);
for(int i=size;i>1;i--)
{
swap(s[1],s[i]);
heapadjust(s,1,i-1,compare);
}
}
int main()
{
//freopen("123.txt","r",stdin);
int n,i;
while(cin>>n)
{
for(i=0;i<n;i++)
scanf("%d",&da[i]);
heapsort(da,n,cmp);//参数(数组首地址,个数,比较函数)
for(i=0;i<n;i++)
printf("%d ",da[i]);
}
return 0;
}