不知道錯哪,求大佬救救俺
利用隨機函式產生N個隨機整數(200以上),對這些數進行由小到大的排序。
要求:采用堆排序。
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#define MaxSize 100
typedef struct
{
int key;
}HeapType;
void HeapAdjust(HeapType h[],int n,int m)
{
int i=m;
h[0]=h[i];
int j=2*i;
while(j<=n)
{
if (j<n&&h[j].key<h[j + 1].key)
{
j=j+1;
}
if(h[j].key>h[0].key)
{
h[i]=h[j];
i=j;
j=2*i;
}
else
{
break;
}
}
h[i]=h[0];
}
void HeapSort(HeapType h[],int n)
{
//初建堆
int i;
for (i=n/2;i>0;i--)
{
HeapAdjust(h,i,n);
}
//調整
for (i=n;i>1;i--)
{
h[0]=h[1];
h[1]=h[i];
h[i]=h[0];
HeapAdjust(h,1,i-1);
}
}
void ShowResult(HeapType *h, int n) //輸出結果
{
int i;
for(i=1;i<=n;i++)
{
printf("%d\t", h[i]);
if (i%10==0)
{
printf("\n");
}
}
}
void RandNum(HeapType *h,int n)
{
int i;
srand((unsigned)time(NULL)); //初始化亂數
for(i=1;i<=n;i++)
{
h[i].key=rand()%400+200; //產生200以上的亂數
printf("%d\t ",h[i]);
if(i%10==0) //每行輸出10個數
{
printf("\n");
}
}
}
int main()
{
int n;
HeapType h[n+1];
printf("產生隨機整數的個數:\n");
scanf("%d",&n) ;
printf("產生的隨機待排序列為:\n");
RandNum(h,n);
HeapSort(h,n);
printf("排序結果為:\n");
ShowResult(h,n);
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/247480.html
標籤:疑難問題
上一篇:mysql 主從復制求教
下一篇:C語言基礎
