堆排序需要两个主要函数 1.HeapAdust 主要功能是沿着key较大的孩子节点向下筛选。刚建大顶堆的时候需要从length/2的子父亲开始,逐渐建立大顶堆。然后让最大的跟最后的元素交换。此时要从新对unordered 的堆进行调整。主要程序如下:
头函数:c9-7
#define MAX_SIZE 20
typedef int KeyType;
struct RedType
{
KeyType key;
InfoType otherinfo;
};
struct SqList
{
RedType r[MAX_SIZE];
int length;
};
c10-1
#define EQ(a,b) ((a)==(b))
#define LT(a,b) ((a)<(b))
#define LQ(a,b) ((a)<=(b))
程序:
#include<stdio.h>
typedef int InfoType;
#include"c9-7.h"
#include"c10-1.h"
typedef SqList HeapType;
void HeapAdjust(HeapType &H,int s,int m)
{
RedType rc;
int j;
rc=H.r[s];
for(j=2*s;j<=m;j*=2)
{
if(j<m&<(H.r[j].key,H.r[j+1].key))
++j;
if(!LT(rc.key,H.r[j].key))
break;
H.r[s]=H.r[j];
s=j;
}
H.r[s]=rc;
}
void HeapSort(HeapType &H)
{
RedType t;
int i;
for(i=H.length/2;i>0;--i)
HeapAdjust(H,i,H.length);
for(i=H.length;i>1;--i)
{
t=H.r[1];
H.r[1]=H.r[i];
H.r[i]=t;
HeapAdjust(H,1,i-1);
}
}
void print(HeapType H)
{
int i;
for(i=1;i<=H.length;i++)
printf("(%d,%d)",H.r[i].key,H.r[i].otherinfo);
printf("\n");
}
#define N 8
void main()
{
RedType d[N]={{49,1},{38,2},{65,3},{97,4},{76,5},{13,6},{27,7},{49,8}};
HeapType h;
int i;
for(i=0;i<N;i++)
h.r[i+1]=d[i];
h.length=N;
printf("排序前:\n");
print(h);
HeapSort(h);
printf("排序后:\n");
print(h);
}
结果:
