Nikolai Neverov
Nikolai Neverov

Reputation: 25

QuickSort with Many Elements causes StackOverflowError

Good day! I am getting a StackOverflowError when running my quickSort algorithm. This error occurs when elements in the array > 50 000.

My code is below :

public void recQuickSort(int left, int right)
{
    if(right-left <= 0)
        return;
    else {
        long pivot = a[right];
        int partition = partitionIt(left, right, pivot);
        recQuickSort(left, partition-1);  
        recQuickSort(partition+1, right); 
    }
}
public int partitionIt(int left, int right, long pivot) {
    int leftPtr = left - 1;
    int rightPtr = right;
    while (true) {
        while (a[++leftPtr] < pivot) ;
        while (rightPtr > 0 && a[--rightPtr] > pivot) ;
        if (leftPtr >= rightPtr)
            break;
        else
            swap1(leftPtr, rightPtr);
    }
        swap1(leftPtr, right);
        return leftPtr;
}

public void swap1(int dex1, int dex2)  // Permutation of two elements
{
    long temp;
    temp = a[dex1];
    a[dex1] = a[dex2];
    a[dex2] = temp;
}

How can I fix this error when elements > 50 000?

Upvotes: 0

Views: 257

Answers (1)

rcgldr
rcgldr

Reputation: 28828

Only recurse on the smaller partition, then update left or right and loop back for the larger partition. This will prevent stack overflow (limit to log2(n) stack frames), but won't prevent worst case time complexity O(n^2).

public void recQuickSort(int left, int right)
{
    while(true){
        if(right-left <= 0)
            return;
        else {
            long pivot = a[right];
            int partition = partitionIt(left, right, pivot);
            if((partition - left) <= (right - partition)){
                recQuickSort(left, partition-1);
                left = partition+1;
            } else {
                recQuickSort(partition+1, right);
                right = partition-1;
            }
        }
    }
}

Upvotes: 1

Related Questions