简体   繁体   English

带有尾递归的C ++快速排序

[英]C++ quicksort with tail recursion

Hy folks, 大家好

im having some trouble with quicksort in c++. 即时通讯在c ++中使用quicksort有麻烦。 At the worst-case with an sorted array (either with growing or declining values) i get an stackoverflow at arrays with ~900 elements. 在最坏的情况下,使用排序数组(值递增或递减)时,在具有〜900个元素的数组上,我得到了stackoverflow。 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. 这篇Wikipedia文章之后,我只是将return作为最后一个示例添加到了我的quickSort上次调用中。 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. 如果使用Hoare类型的分区方案,则wall或wall + 1可能指向枢轴值。 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). 您可以在分区中添加一个检查,以便返回的索引始终指向枢轴值(而不是有时指向枢轴值之前的1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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