简体   繁体   中英

QuickSort Algorithm “StackOverFlowError”

I am implementing the "QuickSort" algorithm provided through GeeksForGeeks. I am sorting an input size of 50K random numbers, I get a error message saying "StackOverFlowError". Is this a case where the recursive call doesn't know when to reach its base case? The crash is happening at line 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);
    }
}

Is this a case where the recursive call doesn't know when to reach its base case?

This method works with smaller arrays. It would not work at all if it didn't reach the base case. So, no.

You're running out of stack size because you're keeping a copy of the array in memory for each time you enter into recursion.

I don't see any problem with you code. It must be the stack size, try increasing it using

Setting it to 2 MB.

java -Xss2m QuickSort

If you are on IDE, change/add it in Run Configuration of IntelliJ/Ecllipse.

Java does not save arrays on stack. It saves them in heap instead. So you just copy a reference to the array in the heap and NOT an array. And when you pass arrays to methods you pass it by reference. So to your question. I have the same problem. And if you made stack size bigger it just will take longer to throw StackOverFlow. So it`s not the solution. If I will found it I will added it here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM