快速排序创建Stackoverflow

时间:2012-10-15 02:40:58

标签: c# stack-overflow quicksort

我有一个执行快速排序的应用程序。它工作正常,直到我开始处理一些更大的数字(我首先得到它10000000)。我知道Stackoverflow是由递归引起的,但我无法理解为什么我的应用程序会因此而被轰炸。任何意见,将不胜感激。这是我的代码:

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

    }
}

1 个答案:

答案 0 :(得分:1)

好。您的代码将在log2 10000000和10000000级别之间递归。

取决于可以使用大量堆栈空间的编译器中的尾递归优化(如果有的话)。

相关问题