堆排序问题
大家能不能写一个堆排序的算法呀,我写的这个编译的时候说什么变量列表语法错误。路过的朋友请帮写一个能运行的,顺便让它也输出。
#include <stdio.h>
#include <malloc.h>
#define MAXITEM 100
struct rec
{
int key;
int data;
};
struct rec sqlist[MAXITEM];
void sift(sqlist r,int l,int m) /*sorted element from r[l]~r[m]*/
{
int i,j;
struct rec x;
i=l;
j=2*i;
x=r[i];
while(j <m)
{
if(j <m&&r[j].key <r[j+1].key)j++;
if(x.key <r[j].key)
{
r[i]=r[j];
i=j;
j=2*i;
}
else j=m+1; /*shift have completed,and set j=m+1 to quit the cicle*/
}
r[i]=x;
}
int main()
{
sqlist r;
int n;
int i;
struct rec m;
for(i=n/2;i> =1;i--) sift(r,i,n); /*build the inittal heap*/
for(i=n;i> =2;i--) /*cicle for n-1 times to complet the heapsort*/
{
m=r[i]; /*shift the first element and the last element*/
r[i]=r[l];
r[l]=m;
sift(r,l,i-1); /**/
}
getch();
return 0;
}
堆排序,大家帮看看为什么错了
提示:错误 heapsort.c 12: 变量列表语法错误
[解决办法]
#include <stdio.h>
#include <malloc.h>
#define MAXITEM 100
struct rec
{
int key;
int data;
};
struct rec sqlist[MAXITEM];
void sift(sqlist r,int l,int m) /*sorted element from r[l]~r[m]*/
{
int i,j;
struct rec x;
i=l;
j=2*i;
x=r[i];
while(j <=m)//修改处
{
if(j <m&&r[j].key <r[j+1].key)++j;//修改处
if(x.key <r[j].key)
{
r[i]=r[j];
i=j;
} //修改处
r[i]=x;
}
int main()
{
sqlist r;//未初始化
int n=MAXITEM;
int i;
struct rec m;
for(i=n/2;i> =0;--i)sift(r,i,n); /*build the inittal heap*/
for(i=n;i> 1;--i) //修改处 /*cicle for n-1 times to complet the heapsort*/
{
m=r[i]; /*shift the first element and the last element*/
r[i]=r[l];
r[l]=m;
sift(r,1,i-1); //这里是阿拉伯数字1 /**/
}
getch();
return 0;
}