Sorting 递归冒泡排序

Sorting 递归冒泡排序,sorting,bubble-sort,Sorting,Bubble Sort,我在谷歌上搜索过,但找不到任何相关信息。我在寻找各种类型的排序,正如您在我前面的问题中所看到的,我想知道是否有人知道递归冒泡排序代码。对我来说,这个想法听起来很可笑,但我想做好准备,我很好奇这是否可以做到。我相信这是可以的,就像我的一位教授过去问他的学生的那样。我不认为他会重复问题,但我变得好奇,想知道是否有递归冒泡排序的代码。这当然是可能的,因为任何迭代算法都可以转换为递归算法,反之亦然 这里有一个方法,我们可以做到这一点。为了简单起见,我使用C++,假设输入都是整数。 void bubble

我在谷歌上搜索过,但找不到任何相关信息。我在寻找各种类型的排序,正如您在我前面的问题中所看到的,我想知道是否有人知道递归冒泡排序代码。对我来说,这个想法听起来很可笑,但我想做好准备,我很好奇这是否可以做到。我相信这是可以的,就像我的一位教授过去问他的学生的那样。我不认为他会重复问题,但我变得好奇,想知道是否有递归冒泡排序的代码。

这当然是可能的,因为任何迭代算法都可以转换为递归算法,反之亦然

这里有一个方法,我们可以做到这一点。为了简单起见,我使用C++,假设输入都是整数。
void bubbleSort(std::vector<int>& list) {
    /* Make one pass of swapping elements. If anything was swapped,
     * repeat this process.
     */
    if (swapPass(list)) {
        bubbleSort(list);
    }
}

/* Does a pass over the array, swapping adjacent elements if they're
 * out of place. Returns true if anything was swapped and false
 * otherwise.
 */
bool swapPass(std::vector<int>& list) {
    return recSwapPass(list, 0, false);
}

/* Does a swap pass starting from index given information about
 * whether a swap was made on the pass so far. Returns true if across
 * the entire pass a swap was made and false otherwise.
 */
bool recSwapPass(std::vector<int>& list, unsigned index,
                 bool wasSwapped) {
    /* Base case: If we're at the end of the array, then there's
     * nothing to do and we didn't swap anything.
     */
    if (index + 1 >= list.size()) return wasSwapped;

    /* Compare the current element against the next one and see if
     * they need to swap.
     */
    if (list[index] > list[index + 1]) {
        std::swap(list[index], list[index + 1]);
        return recSwapPass(list, index + 1, true);
    } else {
        return recSwapPass(list, index + 1, wasSwapped);
    }
}

有趣的是,这里的每个递归函数都是尾部递归的,所以一个好的优化编译器应该能够生成非递归代码。换句话说,一个好的编译器应该生成与我们迭代编写的代码几乎相同的代码。如果我有时间,我会看看这是否真的发生了-

复制品?我想你不会想要的——冒泡排序的优点之一是它具有较低的内存开销。你可以让它简单地递归,比如让算法切换两个值,然后递归。这是真的,我无法想象有人会想早点这样做。冒泡排序通常被定义为一种迭代算法。它可以简单地转换为递归形式,但这可能会降低它的效率,而且在这方面它已经不是最尖锐的方法了。。。那么,问题是为什么?我确实想到了。。。