簡體   English   中英

QuickSort算法“ StackOverFlowError”

[英]QuickSort Algorithm “StackOverFlowError”

我正在實現通過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);
    }
}

這是遞歸調用不知道何時達到基本情況的情況嗎?

此方法適用於較小的數組。 如果沒有達到基本情況,它將根本無法工作。 所以不行。

您用完了堆棧大小,因為每次進入遞歸時都會在內存中保留陣列的副本。

我看不到您的代碼有任何問題。 它必須是堆棧大小,嘗試使用增加它

將其設置為2 MB。

java -Xss2m QuickSort

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

Java不會將數組保存在堆棧中。 而是將它們保存在堆中。 因此,您只需將引用復制到堆中的數組而不是數組。 當您將數組傳遞給方法時,可以通過引用傳遞它。 所以對你的問題。 我也有同樣的問題。 而且,如果您增大堆棧大小,則拋出StackOverFlow所需的時間會更長。 因此,這不是解決方案。 如果找到它,則將其添加到此處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM