#include <stdio.h>
#include <algorithm>
using namespace std;
int a[100]={0,2,1,3,6,5,4,9,7,8,0}, len = 10; //下标从1开始
void heapAdjust(int s, int l)
{
int temp = a[s];
for(int j = 2*s; j <= l; j *= 2)
{
if(j < l && a[j] < a[j+1])
{
++j;
}
if(a[j] <= temp)
{
break;
}
a[s] = a[j];
s = j;
}
a[s] = temp;
}
void heapSort()
{
int tmp = len / 2;
for(int i = tmp; i > 0; i--)
{
heapAdjust(i, len);
}
for(int i = len; i > 1; i--)
{
swap(a[i],a[1]);
heapAdjust(1, i-1);
}
}
int main()
{
heapSort();
for(int i = 1; i <= 10; i++)
{
printf("%d ", a[i]);
}
getchar();
return 0;
}
[大话数据结构] 9.7 堆排序
最新推荐文章于 2020-06-05 15:55:32 发布