Quicksort generates exit code -1073741571 (0xC00000FD) when trying to sort a large sorted container

-1

Im trying to implement a working quicksort, the Lomuto variant. I am using the pseudo code from wikipedia. https://en.wikipedia.org/wiki/Quicksort

void quickSortLomuto(int *first, int *last) {
    if(first < last){
        int *pivot= partitionLomuto(first,last);
        quickSortLomuto(first, pivot- 1);
        quickSortLomuto(pivot+ 1,last);
    }
}
int* partitionLomuto(int* first, int* last) {
    int pivot = *last;
    int *i = first;
    for(int* j = first;j <= last -1;j++){

        if(*j < pivot){
            std::swap(*i,*j);
            i++;
        }
    }
    std::swap(*i,*last);
    return i;
}

It works fine for large containers with random numbers. it breaks down and generate exit code -1073741571 (0xC00000FD) for sorted containers. For really small sorted containers it works but if the container has a size greater than 1 00 000 it crashes with the error code above

c++
quicksort
asked on Stack Overflow Apr 14, 2019 by john denver

1 Answer

1

The reason is twofold: First, you use the worst possible pivot value. For already sorted arrays, it takes O (n^2) execution time. Commonly used strategies are to use a random item as the pivot value, or the middle item, or the median of the first, last and middle item.

The other reason is that your stack overflows, because of the way you do recursion. To avoid this: Find the smaller range and sort it recursively. Then sort the larger range not using recursion, but within the same function, by changing the "first" and "last" parameter. That way, the depth of the stack is at most log n.

If your goal is to copy the algorithm from Wikipedia, your code is fine, and the crash is just expected. If your goal is to sort data, then the pseudocode you copied is just not very good.

answered on Stack Overflow Apr 14, 2019 by gnasher729

User contributions licensed under CC BY-SA 3.0