QuickSort算法“ StackOverFlowError”

时间:2019-03-19 19:09:30

标签: java stack-overflow quicksort

我正在实现通过GeeksForGeeks提供的“ QuickSort”算法。 我正在对50K个随机数字的输入大小进行排序,我收到一条错误消息“ StackOverFlowError”。这是递归调用不知道何时达到基本情况的情况吗?崩溃发生在第58行。

int partition(int arr[], int low, int high)
{
    int pivot = arr[high];
    int i = (low-1); // index of smaller element
    for (int j=low; j<high; j++)
    {
        // If current element is smaller than or
        // equal to pivot
        if (arr[j] <= pivot)
        {
            i++;

            // swap arr[i] and arr[j]
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

    // swap arr[i+1] and arr[high] (or pivot)
    int temp = arr[i+1];
    arr[i+1] = arr[high];
    arr[high] = temp;

    return i+1;
}


/* The main function that implements QuickSort()
  arr[] --> Array to be sorted,
  low  --> Starting index,
  high  --> Ending index */
void sort(int arr[], int low, int high)
{
    if (low < high)
    {
        /* pi is partitioning index, arr[pi] is
          now at right place */
        int pi = partition(arr, low, high);

        // Recursively sort elements before
        // partition and after partition
        sort(arr, low, pi-1); // Line 58, on my IDE
        sort(arr, pi+1, high);
    }
}

3 个答案:

答案 0 :(得分:0)

  

在这种情况下,递归调用不知道何时到达   基本情况?

此方法适用于较小的数组。如果没有达到基本情况,它将根本无法工作。所以,不。

您用完了堆栈大小,因为每次进入递归时都会在内存中保留阵列的副本。

答案 1 :(得分:0)

我看不到您的代码有任何问题。它必须是堆栈大小,尝试使用

增加它

设置为2 MB。

TransferDataSet

如果您使用的是IDE,请在IntelliJ / Ecllipse的“运行配置”中进行更改/添加。

答案 2 :(得分:0)

Java不会将数组保存在堆栈中。而是将它们保存在堆中。因此,您只需将引用复制到堆中的数组而不是数组。当您将数组传递给方法时,可以通过引用传递它。所以对你的问题。我也有同样的问题。而且,如果您增大堆栈大小,则抛出StackOverFlow所需的时间会更长。因此,这不是解决方案。如果找到了,我会在这里添加。