Quicksort导致堆栈溢出

时间:2013-12-13 18:03:12

标签: c# arrays stack-overflow quicksort

我已经实现了一个整数数组的快速排序,如下所示:

public void Quicksort(int left, int right)
{
    /* The recursive quicksort algorithm consists of four steps:
     * 1. If there are one or less elements in the array to be sorted, return immediately.
     * 2. Pick an element in the array to serve as a "pivot" point. (Usually the left-most element in the array is used.)
     * 3. Split the array into two parts - one with elements larger than the pivot and the other with elements smaller than the pivot.
     * 4. Recursively repeat the algorithm for both halves of the original array.
     */

    int pivot = dataTable[left];

    int l_hold = left;
    int r_hold = right;

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

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

        while ((dataTable[left] <= pivot) && (left < right))
            left++;

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

    dataTable[left] = pivot;
    pivot = left;
    left = l_hold;
    right = r_hold;

    if (left < pivot)
        Quicksort(left, pivot - 1);

    if (right > pivot)
        Quicksort(pivot + 1, right);
}

它运行正常,例如,500 000个随机生成的整数。 如果我用升序或降序整数填充数组,则快速排序会导致大约8800个元素的StackOverflowException。

我用我的小眼睛窥探没有明确的理由。你可以用大量的眼睛来窥探一个理由吗?我可以去找一个运行快速排序的copypasta,但我宁愿找出导致问题的原因。

该方法适用于作为类的一部分的数组,通常使用(索引0,最后一个索引-1)调用。提前数千的感谢!

2 个答案:

答案 0 :(得分:0)

您正在体验Tail递归。简而言之,C#编译器不能很好地完成它。我已经读过如果你在调试中遇到这个问题,你可以尝试在发布模式下进行优化编译,这样可以缓解这个问题。

有更详细的信息here

答案 1 :(得分:0)

您需要添加停止条件。

function() {

if(value == 0) {
break;
} else {
 function())
}

你不能一直打电话给Quicksort。它需要停止/休息条件。

相关问题