Quicksort中的无限循环

时间:2018-05-21 06:08:59

标签: c quicksort

我正在实施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;
}

任何帮助将不胜感激。 感谢。

1 个答案:

答案 0 :(得分:1)

partition()内的这种循环条件可能会以无限循环结束:

while(i<=j)

避免将其更改为

while(i<j)

无论如何,它永远不需要交换两个相同的索引。