【问题标题】:Bubble Sort Recursively冒泡排序递归
【发布时间】:2010-12-16 01:13:30
【问题描述】:

我在 Google 上进行了搜索,但找不到任何相关信息。我一直在寻找各种类型的排序(正如您在我的上一个问题中看到的那样),我想知道是否有人知道递归冒泡排序代码。对我来说,这个想法听起来很荒谬,但我想为事情做好准备,我很好奇这是否可以做到。我相信它可以,因为我的一位教授过去曾问过他的学生。我不认为他会重复问题,但我变得好奇,想知道是否有递归冒泡排序的代码。

【问题讨论】:

  • 我认为您不会想要 - 冒泡排序的优点之一是它具有较低的内存开销。你可以让它简单地递归,例如让算法切换两个值然后递归。
  • 这是真的,我无法想象有人会想早点这样做。更多的是出于好奇。
  • 冒泡排序一般定义为一种迭代算法。它可以简单地转换为递归形式,但这可能会降低它的效率,而且在这方面它已经不是最尖锐的方法......所以,问题是“为什么?”确实想到了……

标签: sorting bubble-sort


【解决方案1】:

当然可以这样做,因为任何迭代算法都可以转换为递归算法,反之亦然。

这是我们可以做到这一点的一种方法。为简单起见,我使用 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);
    }
}

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

【讨论】:

    猜你喜欢
    • 2012-05-28
    • 2013-10-09
    • 2021-06-22
    • 2013-12-02
    • 2021-03-24
    • 2011-12-09
    • 2013-11-29
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多