气泡排序递归

时间:2010-12-16 01:13:30

标签: sorting bubble-sort

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

1 个答案:

答案 0 :(得分:0)

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

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

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

相关问题