堆排序就是利用堆得性质,构建一个堆,然后每次把堆顶元素和最后一个元素交换,然后堆得大小减一,直至结束。
code:
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<iostream>
#include<string>
#include <set>
#include<time.h>
using namespace std ;
#define ll long long
#define mem(a) memset(a,0,sizeof(a))
const double eps = 1e-8;
const int maxn = 110010;
const int inf = 0x3f3f3f3f;
int num[10010];
void heapadjust(int heap[],int parent,int nodes)
{
int root=heap[parent];
int son=parent<<1;
while(son<=nodes)
{
if(son+1<=nodes && heap[son]<heap[son+1])
{
son++;
}
if(root>heap[son])//???
break;
heap[parent]=heap[son];
parent=son;
son=son<<1;
}
heap[parent]=root;
}
void heapbuild(int heap[],int nodes)
{
for(int i = nodes/2; i >= 1;i--)
{
heapadjust(heap,i,nodes);
}
return ;
}
void heapsort(int heap[],int nodes)
{
heapbuild(heap,nodes);
for(int i = nodes; i > 1;i--)
{
int tmp = heap[i];
heap[i] = heap[1];
heap[1] = tmp;
heapadjust(heap,1,i-1);
}
}
int main()
{
//freopen("sample.in", "r", stdin);
//freopen("sample.out", "w", stdout);
int n;
scanf("%d",&n);
for(int i = 1; i <= n;i++)
{
scanf("%d",num + i);
}
heapsort(num,n);
for(int i = 1; i <= n;i++)
{
printf("%d ",*(num+i));
}
printf("\n");
return 0;
}
//¿ÜɪÈã¾Æ