//Heap Sort
#include<stdio.h>
#include<stdlib.h>
void HeapAdjust(int r[],int s,int m)
{
int rc = r[s];
for(int j=2*s;j<=m;j*=2)
{
if(j<m&&r[j]<r[j+1])
++j;
if(rc>=r[j])
break;
r[s]=r[j];
s = j;
}
r[s]=rc;
}
void CreatHeap(int r[],int n)
{
for(int i=n/2;i>0;i--)
HeapAdjust(r,i,n);
}
void HeapSort(int r[],int n)
{
CreatHeap(r,n);
for(int i=n;i>1;--i)
{
int temp = r[1];
r[1] = r[i];
r[i] = temp;
HeapAdjust(r,1,i-1);
}
}
int a[10001];
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
CreatHeap(a,n);
HeapSort(a,n);
for(int i=1;i<=n;i++)
printf("%d ",a[i]);
return 0;
}
算法笔记5.堆排序
最新推荐文章于 2024-07-15 18:41:44 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)