資源簡介
根據嚴蔚敏數據結構書上的偽碼實現的堆排序算法。用戶輸入隨機數的個數,然后程序生成相應個數的隨機數,同時進行堆排序,并輸出排序后的結果。VC++6.0編譯測試通過。

代碼片段和文件信息
#include?
#include?
#include?
void?HeapSort(int?*Lint?length);
void?ShowInfo(int?*Lint?length);
void?MAXHEAPIFY(int?*Lint?nokint?length);
FILE?*fp;
int?main()
{
int?ij;
int?number;
long?startend;
int?*L;
if((fp=fopen(“sort.txt““w“))==NULL)
????{?
????????printf(“cannot?open?file“);
????????exit(0);
????}
printf(“請輸入生成隨機數的個數:“);
scanf(“%d“&number);
L?=?(int?*)malloc((number+1)?*sizeof(int));
//1.產生隨機數
srand((int)time(0));???/*設置隨機數種子*/
fprintf(fp“產生的隨機數是:\n“);
for(i=1;i<=number;i++)???//注意0號單元沒有使用
{
j=rand();
fprintf(fp“%-8d“j);
L[i]?=?j;
}
printf(“\n“);
start?=?clock();
//測試的程序段
//2.堆排序
HeapSort(Lnumber);
fprintf(fp“\n排序的結果是:\n“);
ShowInfo(Lnumber);
end?=?clock();
fprintf(fp“\n程序運行時間?:%ld?毫秒\n“end-start);//單位:毫秒
fclose(fp);
printf(“正在打開文件……\n“);
system(?“notepad?sort.txt“?);
return?0;
}
void?HeapSort(int?*Lint?length){
int?i;
//建立大頂堆
for(?i?=?length/2;?i?>?0;?i--){
MAXHEAPIFY(Lilength);
}
for(?i?=?length;?i>1;?i--){
//交換堆頂與尾部元素
int?swap;
swap?=?L[1];
L[1]?=?L[i];
L[i]?=?swap;
//調整大頂堆
MAXHEAPIFY(L1i-1);
}
}
void?MAXHEAPIFY(int?*Lint?nokint?length){
int?key;
int?j;
key?=?L[nok];
for(?j?=?2?*?nok;?j?<=?length;?j*=2){
if(?j??L[j?+1]?)?j++;?//j為key較小的記錄的下標?***
if(?key?>?L[j]?)?break;?//***
L[nok]?=?L[j];
nok?=?j;
}
L[nok]?=?key;
}
void?ShowInfo(int?*Lint?length){
int?t;
for(t?=?1;t?<=?length;?t?++){
fprintf(fp“%-8d“L[t]);
}
}
?屬性????????????大小?????日期????時間???名稱
-----------?---------??----------?-----??----
?????文件?????188463??2009-10-06?23:44??heapsort\Debug\heapsort.exe
?????文件?????525312??2009-10-06?23:44??heapsort\Debug\heapsort.pdb
?????文件???????7649??2009-10-06?23:44??heapsort\Debug\main.obj
?????文件??????53248??2009-10-06?23:44??heapsort\Debug\vc60.pdb
?????文件???????4302??2009-10-06?22:09??heapsort\heapsort.dsp
?????文件????????539??2009-10-06?22:09??heapsort\heapsort.dsw
?????文件??????41984??2009-10-06?23:44??heapsort\heapsort.ncb
?????文件??????53760??2009-10-06?23:44??heapsort\heapsort.opt
?????文件???????1284??2009-10-06?23:44??heapsort\heapsort.plg
?????文件???????1732??2009-10-06?23:43??heapsort\main.c
?????文件????????154??2009-10-06?23:44??heapsort\sort.txt
?????目錄??????????0??2009-10-07?00:19??heapsort\Debug
?????目錄??????????0??2009-10-06?23:44??heapsort
-----------?---------??----------?-----??----
???????????????878427????????????????????13
- 上一篇:vc6讀寫操作excel2007的簡單demo
- 下一篇:東北大學C++實驗報告
評論
共有 條評論