C语言快速排序的程序不知道哪里出了问题(分数就这么多了)
#include <stdio.h>
int *sqlist()
{
int sz[8];
int j=0;
printf("please input\n");
while (j<8)
{
printf("go on\n");
scanf("%d",&sz[j]);
j++;
}
printf("input over\n");
return (&sz[0]);
}
int *partation (int *low,int *high)
{
int m=*low;
int n;
while(low<high)
{
while((low<high)&&(*high>m)) --high;
n=*high;
*high=*low;
*low=n;
while((low<high)&&(*low<m)) ++low;
n=*high;
*high=*low;
*low=n;
}
*low=m;
return low;
}
void qsort(int *low,int *high)
{
int *q;
if(low<high)
{
q=partation(low,high);
qsort(low,q-1);
qsort(q+1,high);
}
}
void main ()
{
int *temp,*low1,*high1;
temp=sqlist();
low1=temp;
high1=temp+8;
qsort(low1,high1);
while(low1<high1)
{
printf("%d",*low1);
low1++;
}
}
想要实现的功能是输入一个数组,通过快速排序法将其从小到大重新排列并输出。
[解决办法]
改了4处,都用注释标出:
#include <stdio.h>
int *sqlist()
{
static int sz[8]; //sz这数组如果不定义为static,那么该函数结束后就不存在了
int j = 0;
printf("please input\n");
while (j<8)
{
printf("go on\n");
scanf("%d",&sz[j]);
j++;
}
printf("input over\n");
return (&sz[0]);
}
int *partation (int *low,int *high)
{
int m = *low;
int n;
while(low<high)
{
while((low<high)&&(*high>=m)) --high; //必须是high>=m,不然有两个数据相同时就会出现错误
n = *high;
*high = *low;
*low = n;
while((low<high)&&(*low<=m)) ++low; //必须是low<=m
n = *high;
*high = *low;
*low = n;
}
*low = m;
return low;
}
void qsort(int *low,int *high)
{
int *q;
if(low<high)
{
q = partation(low,high);
qsort(low,q-1);
qsort(q+1,high);
}
}
void main ()
{
int *temp,*low1,*high1;
temp = sqlist();
low1 = temp;
high1 = temp+7; //应为7,这样*high1才不会越界
qsort(low1,high1);
while(low1<=high1)
{
printf("%d",*low1);
low1++;
}
}