1

I have written following quick sort algorithm .But it's throwing the stack overflow exception. Any suggestion on how to fix this ..

 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;
            }
        }


    }
6
  • 1
    I'd suggest debugging the code, step by step, and seeing how the values of p, q and r change as you make the recursive call. Based on the error I'd guess they're not changing as they should. Commented Jul 16, 2013 at 16:40
  • 1
    A recursive QuickSort always runs the risk of blowing the stack. But not on an 8 element array. Use the debugger to trace what happens. Commented Jul 16, 2013 at 16:40
  • A hint: Partition() creates 3 segments, not 2. Commented Jul 16, 2013 at 16:42
  • Each recursion should be closer to the base case ! Commented Jul 16, 2013 at 16:42
  • The recursive call QuickSort(input, p, q ); QuickSort(input, q, r); looks suspicious to me. There should be either a q-1 or a q+1. Commented Jul 16, 2013 at 16:46

1 Answer 1

1

Your QuickSort method does not stop after partitioning in case it is already sorted.

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This still looks like it could easily get stuck. And produce unsorted output.
Still overflows and doesn't sort anymore

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.