//用满二叉树存储,从n/2处开始递归向上调整(n/2后均为叶子节点,无需调整)使得根最大
//满二叉树顺序存储,左子2i,右子2i+1;
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define ARRAY_SIZE 1000
#define RANDOM_SIZE 100
int buf [ARRAY_SIZE];
int n;
max_heap(int x)
{
int l=2*x,r=l+1,large=x;
if(l<=n&&buf[l]>buf[x])large=l;
if(r<=n&&buf[r]>buf[x])large=r;
if(large!=x)
{
int tmp=buf[large];buf[large]=buf[x];buf[x]=tmp;
max_heap(large);//recurrence adjust
}
}
int main()
{
srand((unsigned int )time(0));
int i;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)buf[i]=rand()%RANDOM_SIZE;
for(i=1;i<=n;i++)printf("%d ",buf[i]);
printf("*\n");
//creat random value of buffer and print
//build_heap
for(i=n/2;i>0;i--)
{
max_heap(i);
}
for(i=1;i<=n;i++)printf("%d ",buf[i]);
}
}
时间: 2024-10-17 02:13:33