跳转至

冒泡排序

本页面将简要介绍冒泡排序。

定义

冒泡排序(英语:Bubble sort)是一种简单的排序算法。由于在算法的执行过程中,较小的元素像是气泡般慢慢「浮」到数列的顶端,故叫做冒泡排序。

bubble sort animate example

过程

它的工作原理是每次检查相邻两个元素,如果前面的元素与后面的元素满足给定的排序条件,就将相邻两个元素交换。当没有相邻的元素需要交换时,排序就完成了。

经过 \(i\) 次扫描后,数列的末尾 \(i\) 项必然是最大的 \(i\) 项,因此冒泡排序最多需要扫描 \(n-1\) 遍数组就能完成排序。

性质

稳定性

冒泡排序是一种稳定的排序算法。

时间复杂度

在序列完全有序时,冒泡排序只需遍历一遍数组,不用执行任何交换操作,时间复杂度为 \(O(n)\)

在最坏情况下,冒泡排序要执行 \(\frac{(n-1)n}{2}\) 次交换操作,时间复杂度为 \(O(n^2)\)

冒泡排序的平均时间复杂度为 \(O(n^2)\)

代码实现

伪代码

\[ \begin{array}{ll} 1 & \textbf{Input. } \text{An array } A \text{ consisting of }n\text{ elements.} \\ 2 & \textbf{Output. } A\text{ will be sorted in nondecreasing order stably.} \\ 3 & \textbf{Method. } \\ 4 & \textbf{for } i\gets0\textbf{ to }n-1\\ 5 & \qquad flag\gets False\\ 6 & \qquad\textbf{for }j\gets0\textbf{ to }n-1-i\\ 7 & \qquad\qquad\textbf{if }A[j]>A[j + 1]\\ 8 & \qquad\qquad\qquad flag\gets True\\ 9 & \qquad\qquad\qquad \text{Swap } A[i]\text{ and }A[i + 1]\\ 10 & \qquad\textbf{if }!flag\textbf{ break; }\\ \end{array} \]

记忆口诀

n个数字来排队,

两两相比做交换,

外层循环n-1,

内层循环n-1-i,

大前小,小前大,

false,false,break。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// 假设数组的大小是 n,冒泡排序从数组下标 0 开始
void bubble_sort(int a[], int n) // 或 *a 指针传递
{
    for (int i = 0; i < n; i++)
    {
        flag = false;
        for (int j = 0; j < n - 1 - i; j++)
        {
            if (a[j] > a[j + 1]) //大的在前用<   小的在前用>
            {
                swap(a[j], a[j + 1]);
                flag = true;
            }
        }
        if (!flag)
            break;
    }
}
1
2
3
4
5
6
7
8
9
def bubble_sort(a, n):
    for i in range(len(a)-1):
        flag = False
        for j in range(len(a)-1-i):
            if a[j] > a[j + 1]:
                flag = True
                a[j], a[j + 1] = a[j + 1], a[j]
        if not flag:
            break
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
 // 假设数组的大小是 n + 1,冒泡排序从数组下标 1 开始
    static void bubble_sort(int[] a, int n) {
    for (int i = 0; i < n; i++)
    {
        flag = false;
        for (int j = 0; j < n - 1 - i; j++)
        {
            if (a[j] > a[j + 1])
            {
                int t = a[j];
                a[j] = a[j+1];
                a[j+1] = t;
                flag = true;
            }
        }
        if (!flag)
            break;
    }
}