大顶堆排序
#include\"stdio.h\" #include\"stdlib.h\"
//*****************************************
typedef int KeyType; int n=0;
typedef struct{ //定义记录类型 KeyType key;//关键字项 }RedType;
typedef struct{
RedType r[21];//r[0]闲置或用作哨兵单元
int length;//顺序表长度
}Sqlist,*Head; //顺序表类型
//*****************************************
//调整函数
void HeapAdjust(Sqlist &H, int s, int m) {int j;
RedType rc;
rc = H.r[s];
for (j=2*s; j<=m; j*=2)
{if (jif (rc.key >= H.r[j].key) break; H.r[s] = H.r[j]; s = j; }H.r[s] = rc; // 插入 } // HeapAdjust
//*****************************************
//排序输出函数
void HeapSort(Sqlist &H) {
int i;
printf(\"请输入要排序的数的的个数(20以内): \\n\");//建立堆
scanf(\"%d\
printf(\"\\n请输入这%d个数(用空格隔开): \\n\
H.length=n; for(i=1;i<=n;i++) scanf(\"%d\
RedType temp;
for (i=H.length/2; i>0; --i) HeapAdjust ( H, i, H.length ); for (i=H.length; i>1; --i) { temp=H.r[i];H.r[i]=H.r[1]; H.r[1]=temp;
HeapAdjust(H, 1, i-1); }
printf(\"\\n大顶堆排序结果如下:\\n\");//输出堆 for(i=1;i<=n;i++) printf(\"%d \
} // HeapSort
//***************************************** //主函数 void main() { Sqlist H;
HeapSort(H);//堆排序 printf(\"\\n\");
}
运行结果如下: