資源簡介
根據(jù)嚴(yán)蔚敏數(shù)據(jù)結(jié)構(gòu)書上的偽碼實(shí)現(xiàn)的堆排序算法。用戶輸入隨機(jī)數(shù)的個(gè)數(shù),然后程序生成相應(yīng)個(gè)數(shù)的隨機(jī)數(shù),同時(shí)進(jìn)行堆排序,并輸出排序后的結(jié)果。VC++6.0編譯測(cè)試通過。

代碼片段和文件信息
#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(“請(qǐng)輸入生成隨機(jī)數(shù)的個(gè)數(shù):“);
scanf(“%d“&number);
L?=?(int?*)malloc((number+1)?*sizeof(int));
//1.產(chǎn)生隨機(jī)數(shù)
srand((int)time(0));???/*設(shè)置隨機(jī)數(shù)種子*/
fprintf(fp“產(chǎn)生的隨機(jī)數(shù)是:\n“);
for(i=1;i<=number;i++)???//注意0號(hào)單元沒有使用
{
j=rand();
fprintf(fp“%-8d“j);
L[i]?=?j;
}
printf(“\n“);
start?=?clock();
//測(cè)試的程序段
//2.堆排序
HeapSort(Lnumber);
fprintf(fp“\n排序的結(jié)果是:\n“);
ShowInfo(Lnumber);
end?=?clock();
fprintf(fp“\n程序運(yùn)行時(shí)間?:%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;
//調(diào)整大頂堆
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較小的記錄的下標(biāo)?***
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]);
}
}
?屬性????????????大小?????日期????時(shí)間???名稱
-----------?---------??----------?-----??----
?????文件?????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
評(píng)論
共有 條評(píng)論