Quicksort进入无限循环

时间:2012-10-31 08:29:18

标签: c algorithm quicksort

我正在尝试为quicksort编写代码,但它继续在infinte循环中运行,我已经努力在下面的代码中找到错误,请有人帮忙。

#include<stdio.h>
#include<stdlib.h>

int arr[100];

void quicksort(int low,int high)
{
    int i = low,j = high,pivotIndex,pivot;
    pivotIndex = rand()%20;
    pivot = arr[pivotIndex];

    if(i>=j)
        return;

    while(i<j)
    {

        while(arr[i]<pivot && i<j)
        {
            i++;
        }

        while(arr[j]>pivot && j>i)
        {
            j--;
        }

        if(i<j)
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }

    }
    quicksort(low,i);
    quicksort(i+1,high);
}

int main()
{
    int i,j,temp;

    for(i=0;i<20;i++)
        arr[i] = rand()%21;

    for(i=0;i<20;i++)
        printf("%d ",arr[i]);
    printf("\n");

    quicksort(0,19);

    for(i=0;i<20;i++)
            printf("%d ",arr[i]);
    printf("\n");

    return 0;
}

3 个答案:

答案 0 :(得分:7)

您的数据透视表选择错误,您应选择(索引)范围[low,high)中的数据透视表,同时选择范围[0,20)中的数据透视:

pivotIndex = rand()%20;

稍后会使分区不顺利,而后来用于递归的i的值将是错误的。


编辑:

另一个问题是分区,它还应该考虑如何处理pivot元素及其重复项 - 应该有某种“tie breaker” - pivot应该转到数组的一侧(或者一些替代)。
例如,假设数据透视为5,数组为[5,3,8,5]
你只需要一遍又一遍地无限地交换5,这绝对是错误的。

答案 1 :(得分:1)

作为一个排序插件的作者,我可以向你保证,重新发明这些算法可以真正咬你的谚语。 ; O)

必须特别注意(如上所述)选择枢轴,算术将如何影响枢轴值(例如,VBA在浮点中执行其整数运算,导致各种奇怪),其中'剩饭'去,最后一步如何处理最后一个分区(你不会是第一个跳过这里的几条记录)。

以下是使用多种语言排序算法的链接:

http://rosettacode.org/wiki/Sorting_algorithms/Quicksort

答案 2 :(得分:-1)

 pivotIndex = rand()%20;
 pivot = arr[pivotIndex];

每次调用快速排序时,您的pivotIndex可能不在范围内(低,高)。 你可以使用

pivotIndex = low+rand()%(high-low);

我确信这会生成范围内的pivotIndex。

相关问题