c用的比较粗浅,网上观摩了一下都比我的精致,难得能运行成功,先mark一下。
-
#include<stdio.h>
-
/*void heapAdjust(int num[],int i,int size)
-
{
-
int rchild;
-
if(2*i+2>=size)
-
rchild==-32768;
-
else
-
rchild=num[2*i+2];
-
int temp=num[i];
-
int lchild=num[2*i+1];
-
printf(" ---called heapadjust:\n");
-
printf(" root:%d,lchild:%d,rchild:%d\n",temp,lchild,rchild);
-
if(temp<lchild)
-
{
-
if(temp<rchild)
-
{
-
if(lchild<rchild)
-
{
-
temp=rchild;
-
num[2*i+2]=num[i];
-
num[i]=temp;
-
}
-
else
-
{
-
num[i]=num[2*i+1];
-
num[2*i+1]=temp;
-
}
-
}
-
else
-
{
-
num[i]=num[2*i+1];
-
num[2*i+1]=temp;
-
}
-
}
-
else
-
{
-
if(temp<rchild)
-
{
-
num[i]=num[2*i+2];
-
num[2*i+2]=temp;
-
}
-
}
-
}*/
-
void heapAdjust(int num[],int i,int size)
-
{
-
int temp=num[i];
-
int lchild=2*i+1;
-
while(lchild<size)
-
{
-
if((lchild<size-1)&&(num[lchild]<num[lchild+1]))
-
lchild++;
-
if(temp<num[lchild])
-
{
-
num[i]=num[lchild];
-
i=lchild;
-
lchild=2*i+1;
-
}
-
else
-
break;
-
-
}
-
num[i]=temp;
-
}
-
int buildHeap(int num[],int size)
-
{
-
int i;
-
for(i=size/2-1;i>=0;i--)
-
{
-
printf("BUILD HEAP\n");
-
heapAdjust(num,i,size);
-
printf(" ");
-
for(int i=0;i<size;i++)
-
{
-
printf("%d",num[i]);
-
printf(",");
-
}
-
printf("------Round: %d to build the heap.\n",i);
-
}
-
}
-
int heapSort(int num[],int size)
-
{
-
int i,temp;
-
for(i=size-1;i>=0;i--)
-
{
-
buildHeap(num,i+1);
-
printf("\n");
-
printf("---->move the biggest one to later position-----\n");
-
printf("%d,%d,%d,--->",i,num[0],num[i]);
-
temp=num[0];
-
num[0]=num[i];
-
num[i]=temp;
-
printf("%d,%d--\n",num[0],num[i]);
-
printf("now the num[] is:");
-
for(int j=0;j<size;j++)
-
{
-
printf("%d,",num[j]);
-
//printf(" \n");
-
}
-
printf("\n");
-
printf("\n");
-
}
-
}
-
void main()
-
{
-
/*int num[6];
-
printf("Enter 6 numbers:\n");
-
for(int i=0;i<6;i++)
-
{
-
scanf("%d",&num[i]);
-
}*/
-
int num[]={-6,89,47,-99,32762,34,67,-345};
-
int size=sizeof(num)/sizeof(int);
-
heapSort(num,size);
-
printf("-----------------Sorted Array---------------------\n");
-
for(int i=0;i<size;i++)
-
{
-
printf("%d",num[i]);
-
printf(",");
-
}
-
-
-
}
阅读(856) | 评论(0) | 转发(0) |