QuickSort with Many Elements causes StackOverflowError

不打扰是莪最后的温柔 提交于 2019-12-11 16:21:25

问题


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?


回答1:


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;
            }
        }
    }
}


来源:https://stackoverflow.com/questions/47964255/quicksort-with-many-elements-causes-stackoverflowerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!