堆排序~
好像很久没有看排序部分了~这个好像有点难懂~还是先发发代码~~
程序代码:#include<stdio.h>
#include<stdlib.h>
#define MAX 255
int R[MAX]={0};
void Heapify(int s,int m);
void BuildHeap(int n);
void Heap_Sort(int n);
int main()
{
int i=0;
int n=0;
puts("Please input total element number of the sequence:");
scanf("%d",&n);
if (n<=0||n>MAX)
{
printf("n must more than 0 and less than %d.\n",MAX);
exit(0);
}
puts("Please input the elements one by one:");
for (i=1;i<=n;++i)
scanf("%d",&R[i]);
puts("The sequence you input is:");
for (i=1;i<=n;++i)
printf("%4d",R[i]);
Heap_Sort(n);
puts("\nThe sequence after Big head_sort is:");
for (i=1;i<=n;++i)
printf("%4d",R[i]);
puts("");
return 0;
}
void Heapify(int s,int m)
{
/*对R[1..n]进行堆调整,用temp做暂存单元*/
int j=2*s;
int temp=R[s];
while (j<=m)
{
if (R[j]>R[j+1]&&j<m)
j++;
if (temp<R[j])
break;
R[s]=R[j];
s=j;
j*=2;
}
R[s]=temp;
}
void BuildHeap(int n)
{
/*由一个无序的序列建成一个堆*/
int i=0;
for (i=n/2;i>0;--i)
Heapify(i,n);
}
void Heap_Sort(int n)
{
/*对R[1..n]进行堆排序,不妨用R[0]做暂存单元*/
int i=0;
BuildHeap(n);
for (i=n;i>1;--i)
{
R[0]=R[1]; /*将堆顶和堆中最后一个元素记录交换*/
R[1]=R[i];
R[i]=R[0];
Heapify(1,i-1); /*将R[1..i-1]重新调整为堆,仅有R[1]可能违反堆性质*/
}
}









本例应该是个小顶堆~
