简体   繁体   中英

C++ quicksort with tail recursion

Hy folks,

im having some trouble with quicksort in c++. At the worst-case with an sorted array (either with growing or declining values) i get an stackoverflow at arrays with ~900 elements. Tail recursion was an solution i found, but im probably not do it right here, since im not achiving any improvements:

void quickSort(int *array, int start, int end){
    //elementary state
    if (start + 1 > end){
        return;
    }

    //partitioning, retuns position of pivotelemnt
    int wall = partitioning(array, start, end);

    //recursion
    quickSort(array, start, wall-1);
    //tail recursion?
    return quickSort(array, wall + 1, end);
}//quickSort

Following this Wikipedia article i just added the return to my last call of quickSort as the first example there. I dont think that is doing anything though...

edit:

int partitioning(int *array, int start, int end){

    //partitioningborder
    int wall = start;

    for (int i = wall; i < end; ++i){
        if (array[i] <= array[end]){

            //swap an element if needed
            int swap = array[i];
            array[i] = array[wall];
            array[wall] = swap;

            //increment the partitioningborder
            wall++;
        }//if
    }//for

    //place pivotelement
    int swap = array[end];
    array[end] = array[wall];
        array[wall] = swap;

        return wall;
}//partitioning

To avoid stack overflow, the code needs to compare partition sizes, (wall - start) versus (end - wall), recurse on the smaller partition, and loop back for the larger partition. It's not really tail recursion. Something like this:

void quickSort(int *array, int start, int end){
    while(start < end){
        wall = partition(...);   // wall = index to pivot
        // recurse on smaller part, loop on larger part
        if((wall - start) <= (end - wall)){
            quickSort(a, start, wall-1);
            start = wall+1;
        } else {
            quickSort(a, wall+1, end);
            end = wall-1;
        }
    }
}

If using a Hoare type partition scheme, wall or wall+1 may point to the pivot value. You can add a check in partition so that the returned index always points to the pivot value (instead of sometimes pointing to 1 before pivot value).

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