我正在实现Quicksort Algorithm
,但是我有一些error
,我无法理解。
我使用rand()
函数生成随机数。我把这些数字限制在mod(100)
。mod (100)
工作得很好,但当我让它mod(10)
时,它就不工作了。程序运行,但在打印随机未排序数组后停止。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
int a[50];
void quicksort(int l, int r)
{
int s;
if(l<r)
{
s=partition(l, r);
quicksort(l, s-1);
quicksort(s+1, r);
}
}
int partition(int l, int r)
{
int p, i, j, temp;
p = a[l];
i=l;
j=r+1;
while(i<=j)
{
while(a[i]<=p && i<r+1)
i=i+1;
while(a[j]>=p && j>l)
j=j-1;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
temp = a[i];
a[i] = a[j];
a[j] = temp;
temp = a[l];
a[l] = a[j];
a[j] = temp;
return j;
}
int main()
{
int n, i;
printf("Enter number of elements: \n");
scanf("%d", &n);
printf("Random Array: \n");
for(i=0; i<n; i++)
{
a[i] = rand()%100; // The error seems to be here for rand()%10
printf("%d ", a[i]);
}
quicksort(0,n-2);
printf("\n Solution: \n");
for(i=0; i<n; i++)
{
printf("%d ", a[i]);
}
return 0;
}
任何帮助都将不胜感激。
谢谢。
最佳答案
partition()
中的循环条件可能会以无休止的循环结束:
while(i<=j)
避免更改为
while(i<j)
无论如何,它不需要在两个相同的索引处交换。
关于c - Quicksort中的无限循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50442932/