quicksort算法抛出stackoverflow异常错误

时间:2013-07-16 16:38:43

标签: c# algorithm

我写了以下快速排序算法。但是它抛出了堆栈溢出异常。 关于如何解决这个问题的任何建议..

 static void Main(string[] args)
    {
        int[] input={17,12,6,19,23,8,5,10};
        QuickSort(input,0,7);
        foreach (int item in input)
        {
            Console.WriteLine(item);
        }
    }
    static void QuickSort(int[] input,int p , int r)
    {
        if (p<r)
        {
            int q=Partition(input, p, r);
            QuickSort(input, p, q );
            QuickSort(input, q, r);
        }
    }
    static int  Partition(int [] input,int p,int r)
    {
        int pivot = input[r];//pivot element
        int i = p - 1;
        int j = r + 1;
        while (true)
        {
            do
            {
                i = i + 1;
            } while (!(input[i]>=pivot));
            do
            {
                j = j - 1;
            } while (!(input[j] <= pivot));
            //swap
            if (i<j)
            {
                int temp = input[i];
                input[i] = input[j];
                input[j] = temp;
            }
            else
            {
                return j;
            }
        }


    }

1 个答案:

答案 0 :(得分:1)

如果分区已经排序,您的QuickSort方法不会停止。

private static void QuickSort(int[] input, int p, int r) {
    if (p < r) {
        int q = Partition(input, p, r);
        if (q < r) {
            QuickSort(input, p, q);
            QuickSort(input, q, r);
        }
    }
}