数据结构与算法 ~ 排序 ~ 堆排序
/*sort--heapsort*/
#include<stdlib.h>
#include<stdio.h>
#define MAX 100
int create_heap(int *heap){
int e,length=0;
printf("\n=======创建=======\n");
printf("\n请输入数字(退出输入0):");
scanf("%d",&e);
while(e!=0){
heap[++length]=e;
printf("\n请输入数字(退出输入0):");
scanf("%d",&e);
}/*while*/
return length;
}/*create_heap*/
void Print(int *heap,int length,int n){
int i;
printf("\n==当前堆排序结果:==:");
for (i=1;i<=length;++i){
if (i==n) printf("=||=,");
printf("%d,",heap[i]);
}
}
void heapadjust(int *heap,int s,int m){
int j;
heap[0]=heap[s];
for(j=2*s;j<=m;j*=2){
if (j<m && heap[j]<heap[j+1])
++j;
if (heap[0]>heap[j])
break;
heap[s]=heap[j];
s=j;
}/*for*/
heap[s]=heap[0];
}/*heapadjust*/
void heapsort(int *heap,int length){
int i;
for (i=length/2;i>0;--i)
heapadjust(heap,i,length);
Print(heap,length,0);
for(i=length;i>1;--i){
heap[0]=heap[1];
heap[1]=heap[i];
heap[i]=heap[0];
heapadjust(heap,1,i-1);
Print(heap,length,i);
}/*for*/
}
main(){
int length,heap[MAX];
length=create_heap(heap);
Print(heap,length,length+1);
printf("\n堆的长度是%d",length);
printf("\n=======over============\n");
heapsort(heap,length);
Print(heap,length,0);
system("pause");
exit(0);
}
运行结果是:
=======创建=======
请输入数字(退出输入0):59
请输入数字(退出输入0):48
请输入数字(退出输入0):75
请输入数字(退出输入0):96
请输入数字(退出输入0):86
请输入数字(退出输入0):23
请输入数字(退出输入0):37
请输入数字(退出输入0):59
请输入数字(退出输入0):65
请输入数字(退出输入0):14
请输入数字(退出输入0):0
==当前堆排序结果:==:59,48,75,96,86,23,37,59,65,14,
堆的长度是10
=======over============
==当前堆排序结果:==:96,86,75,65,59,23,37,59,48,14,
==当前堆排序结果:==:86,65,75,59,59,23,37,14,48,=||=,96,
==当前堆排序结果:==:75,65,48,59,59,23,37,14,=||=,86,96,
==当前堆排序结果:==:65,59,48,14,59,23,37,=||=,75,86,96,
==当前堆排序结果:==:59,59,48,14,37,23,=||=,65,75,86,96,
==当前堆排序结果:==:59,37,48,14,23,=||=,59,65,75,86,96,
==当前堆排序结果:==:48,37,23,14,=||=,59,59,65,75,86,96,
==当前堆排序结果:==:37,14,23,=||=,48,59,59,65,75,86,96,
==当前堆排序结果:==:23,14,=||=,37,48,59,59,65,75,86,96,
==当前堆排序结果:==:14,=||=,23,37,48,59,59,65,75,86,96,
==当前堆排序结果:==:14,23,37,48,59,59,65,75,86,96,请按任意键继续. . .