Search code examples
c#stack-overflowquicksort

Quick Sort Creates Stackoverflow


I have an application that performs a quick sort. It was working fine till I started handing it some bigger numbers (I first got it at 10000000). I understand that a Stackoverflow is caused by recursion but I can't understand why my application would be bombing out due to it. Any advice would be appreciated. Here's my code:

class quickSort
{
    const int NOOFELEMENTS = 10000000;
    // this is our array to sort
    private int[] arr = new int[NOOFELEMENTS];

    // this holds a number of elements in array
    private int len;

    // Quick Sort Algorithm
    public void QuickSort()
    {
        sort(0, len - 1);
    }

    public void sort(int left, int right)
    {
        int pivot, l_holder, r_holder;

        l_holder = left;
        r_holder = right;
        pivot = arr[left];

        while (left < right)
        {
            while ((arr[right] >= pivot) && (left < right))
            {
                right--;
            }

            if (left != right)
            {
                arr[left] = arr[right];
                left++;
            }

            while ((arr[left] <= pivot) && (left < right))
            {
                left++;
            }

            if (left != right)
            {
                arr[right] = arr[left];
                right--;
            }
        }

        arr[left] = pivot;
        pivot = left;
        left = l_holder;
        right = r_holder;

        if (left < pivot)
        {
            sort(left, pivot - 1);
        }

        if (right > pivot)
        {
            sort(pivot + 1, right);
        }
    }

    public static void Main()
    {
        quickSort q_Sort = new quickSort();

        int[] arr = new int[NOOFELEMENTS];

        Random rnd = new Random();
        for (int i = 0; i < NOOFELEMENTS; i++)
        {
            arr[i] = rnd.Next(0, 1000);
        }
        q_Sort.arr = arr;
        q_Sort.len = q_Sort.arr.Length;

        var startTime = DateTime.Now;

        // Sort the array
        q_Sort.QuickSort();

        Console.WriteLine("Total Time: {0}\n", DateTime.Now - startTime);

    }
}

Solution

  • Well. Your code will recurse between log2 10000000 and 10000000 levels deep.

    Depending on tail-recursion optimizations in the compiler (if any) that can use a lot of stackspace.