C#Quicksort一个具有重复出现值的数组

时间:2014-09-08 13:10:52

标签: c# quicksort

我有快速排序的问题,直到我得到一个或多个重复出现的值才能正常工作。

这个问题似乎已经有一段时间了,我已经找到了几个“解决方案”并讨论了论坛。与实际解决方案最接近的是:Quicksort infinite loop if there are repeating values 问题是,我不能对那个答案发表评论。

但回到我的问题。如何使此代码与重复出现的值一起使用。 (是的,我知道创建一个交换方法,分区方法可能看起来更好,但这与问题无关)

    public void QuickSort(int[] A, int lo, int hi)
    {
        if (lo < hi)
        {
            int pivot = A[(hi-lo)/2+lo]; // I can create a random pivot, but that has the same effect as putting the pivot in the middle. The sorting algorithm doesn't know the values.
            int left = 0;
            int right = hi;
            while (left <= right)
            {
                while (A[left] < pivot)
                    left++;
                while (A[right] > pivot)
                    right--;
                if (left <= right)
                {
                    int temp = A[left];
                    A[left] = A[right];
                    A[right] = temp;
                    left++;
                    right--;
                }
            }
            QuickSort(A, lo, right);
            QuickSort(A, left, hi);
        }
    }

1 个答案:

答案 0 :(得分:0)

似乎你的方法并不是从良好的指数开始。从lo而不是0开始会更好。

public void QuickSort(int[] A, int lo, int hi)
{
    if (lo < hi)
    {
        int pivot = A[(hi-lo)/2+lo]; // I can create a random pivot, but that has the same effect as putting the pivot in the middle. The sorting algorithm doesn't know the values.
        int left = lo;
        int right = hi;
...
    }
}