The Algorithms logo
算法
关于我们捐赠

递归冒泡排序

P
/**
 * @file
 * @author [Aditya Prakash](https://adityaprakash.tech)
 * @brief This is an implementation of a recursive version of the [Bubble sort algorithm](https://www.geeksforgeeks.org/recursive-bubble-sort/)
 *
 * @details
 * The working principle of the Bubble sort algorithm.

 * Bubble sort is a simple sorting algorithm used to rearrange a set of ascending or descending order elements.
 * Bubble sort gets its name from the fact that data "bubbles" to the top of the dataset.
 
 * ### Algorithm

 * What is Swap?

 * Swapping two numbers means that we interchange their values.
 * Often, an additional variable is required for this operation. 
 * This is further illustrated in the following:

 * void swap(int x, int y){
 *     int z = x;
 *     x = y;
 *     y = z;
 * }

 * The above process is a typical displacement process.
 * When we assign a value to x, the old value of x is lost.
 * That's why we create a temporary variable z to store the initial value of x.
 * z is further used to assign the initial value of x to y, to complete swapping.

 * Recursion

 * While the recursive method does not necessarily have advantages over iterative
 * versions, but it is useful to enhance the understanding of the algorithm and
 * recursion itself. In Recursive Bubble sort algorithm, we firstly call the
 * function on the entire array, and for every subsequent function call, we exclude
 * the last element. This fixes the last element for that sub-array.Formally, for
 * `ith` iteration, we consider elements up to n-i, where n is the number of
 * elements in the array. Exit condition: n==1; i.e. the sub-array contains only
 * one element.

 * Complexity
 * Time complexity: O(n) best case; O(n²) average case; O(n²) worst case
 * Space complexity: O(n)

 * We need to traverse the array `n * (n-1)` times. However, if the entire array is
 * already sorted, then we need to traverse it only once. Hence, O(n) is the best case
 * complexity
*/

#include <cassert>   /// for assert
#include <iostream>  /// for IO operations
#include <vector>    /// for std::vector
#include <array>     /// for std::array
#include <algorithm> /// for std::is_sorted

/**
 * @namespace sorting
 * @brief Sorting algorithms
 */
namespace sorting {

/**
 * @brief This is an implementation of the recursive_bubble_sort. A vector is passed
 * to the function which is then dereferenced, so that the changes are
 * reflected in the original vector. It also accepts a second parameter of
 * type `int` and name `n`, which is the size of the array.
 * 
 * @tparam T type of data variables in the array
 * @param nums our array of elements.
 * @param n size of the array
 */
template <typename T>
void recursive_bubble_sort(std::vector<T> *nums, uint64_t n) {
    if (n == 1) {  //!< base case; when size of the array is 1
        return;
    }

    for (uint64_t i = 0; i < n - 1; i++) {  //!< iterating over the entire array
        //!< if a larger number appears before the smaller one, swap them.
        if ((*nums)[i] > (*nums)[i + 1]) {
            std::swap((*nums)[i], (*nums)[i + 1]);
        }
    }

    //!< calling the function after we have fixed the last element
    recursive_bubble_sort(nums, n - 1);
}
}  // namespace sorting

/**
 * @brief Self-test implementations
 * @returns void
 */
static void test() {
    // 1st example. Creating an array of type `int`.
    std::cout << "1st test using `int`\n";
    const uint64_t size = 6;
    std::vector<int64_t> arr;
    // populating the array
    arr.push_back(22);
    arr.push_back(46);
    arr.push_back(94);
    arr.push_back(12);
    arr.push_back(37);
    arr.push_back(63);
    // array populating ends

    sorting::recursive_bubble_sort(&arr, size);
    assert(std::is_sorted(std::begin(arr), std::end(arr)));
    std::cout << " 1st test passed!\n";
    // printing the array
    for (uint64_t i = 0; i < size; i++) {
        std::cout << arr[i] << ", ";
    }
    std::cout << std::endl;

    // 2nd example. Creating an array of type `double`.
    std::cout << "2nd test using doubles\n";
    std::vector<double> double_arr;

    // populating the array
    double_arr.push_back(20.4);
    double_arr.push_back(62.7);
    double_arr.push_back(12.2);
    double_arr.push_back(43.6);
    double_arr.push_back(74.1);
    double_arr.push_back(57.9);
    // array populating ends

    sorting::recursive_bubble_sort(&double_arr, size);
    assert(std::is_sorted(std::begin(double_arr), std::end(double_arr)));
    std::cout << " 2nd test passed!\n";
    // printing the array
    for (uint64_t i = 0; i < size; i++) {
        std::cout << double_arr[i] << ", ";
    }
    std::cout << std::endl;

}

/**
 * @brief Main function
 * @returns 0 on exit
 */
int main() { 
    test();  // run self-test implementations
    return 0;
}
关于此算法

冒泡排序是最简单的排序算法之一,它一次比较两个元素,如果它们顺序错误就交换它们。重复此过程,直到整个序列按顺序排列。

  • 时间复杂度:平均情况下为 O(n ^ 2);最佳情况下为 O(n)
  • 空间复杂度:O(n);请注意,迭代冒泡排序的空间复杂度为 O(1)

步骤

基本情况:如果数组的大小为 1,则返回。

  • 我们需要修复当前子数组的最后一个元素。为此,使用普通冒泡排序遍历整个数组,并执行交换。
  • 接下来,在整个数组上调用该函数,排除最后一个元素(在上面步骤的迭代中已修复)。
  • 重复,直到到达基本情况。

示例

假设给定的数组为:{5, 3, 2, 1, 4}

第一次迭代

  • {5, 3, 2, 1, 4} -> {3, 5, 2, 1, 4} 交换,因为 5 > 3
  • {3, 5, 2, 1, 4} -> {3, 2, 5, 1, 4} 交换,因为 5 > 2
  • {3, 2, 5, 1, 4} -> {3, 2, 1, 5, 4} 交换,因为 5 > 1
  • {3, 2, 1, 5, 4} -> {3, 2, 1, 4, 5} 交换,因为 5 > 4

这次迭代已经固定了 5 的位置。现在,我们将考虑索引为 3 之前的数组。

第二次迭代

  • {3, 2, 1, 4, 5} -> {2, 3, 1, 4, 5} 交换,因为 3 > 2
  • {2, 3, 1, 4, 5} -> {2, 1, 3, 4, 5} 交换,因为 3 > 1
  • {2, 1, 3, 4, 5}; 由于 3 < 4,不交换

注意:由于我们每次迭代都检查少一个元素,因此我们不需要索引为 3 和 4 的元素,即 45,因为 5 已经排好序了。正式地说,对于包含 n 个整数的数组,我们只考虑索引为 n - i 之前的元素,其中 i 是迭代次数。

第三次迭代

  • {2, 1, 3, 4, 5} -> {1, 2, 3, 4, 5} 交换,因为 1 > 2
  • {1, 2, 3, 4, 5}; 由于 2 < 3,不交换

第四次迭代

  • {1, 2, 3, 4, 5}; 由于 1 < 2,不交换

第五次迭代

  • {1, 2, 3, 4, 5}; 由于数组的大小为 1,则返回。

注意:这是基本情况。

伪代码

void bubbleSort(arr[], n)
    if(n==1)
        return;

    for(i = 0; i<n-1; i++)
        if(arr[i] > arr[i+1])
            swap(arr[i], arr[i+1])

    bubbleSort(arr, n-1)

视频解释

解释迭代和递归冒泡排序的视频