This page briefly introduces bubble sort.
Definition
Bubble sort (English: Bubble sort) is a simple sorting algorithm. Since, during its execution, smaller elements slowly “float” to the top of the sequence like bubbles, it is called bubble sort.
Process
It works by checking two adjacent elements each time. If the preceding element and the following element satisfy the given sorting condition, the two adjacent elements are swapped. When no adjacent elements need to be swapped, sorting is complete.
After scans, the final elements of the sequence must be the largest elements. Therefore, bubble sort needs to scan the array at most times to complete sorting.
Properties
Stability
Bubble sort is a stable sorting algorithm.
Time complexity
When the sequence is already completely sorted, bubble sort only needs to traverse the array once and does not perform any swaps, so its time complexity is .
In the worst case, bubble sort performs swaps, so its time complexity is .
The average time complexity of bubble sort is .
Implementation
Pseudocode
C++
// Assume that the array size is n + 1 and bubble sort starts from array index 1
void bubble_sort(int *a, int n) {
bool flag = true;
while (flag) {
flag = false;
for (int i = 1; i < n; ++i) {
if (a[i] > a[i + 1]) {
flag = true;
int t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}
}
}
Python
def bubble_sort(a, n):
flag = True
while flag:
flag = False
for i in range(1, n):
if a[i] > a[i + 1]:
flag = True
a[i], a[i + 1] = a[i + 1], a[i]
Java
// Assume that the array size is n + 1 and bubble sort starts from array index 1
static void bubble_sort(int[] a, int n) {
boolean flag = true;
while (flag) {
flag = false;
for (int i = 1; i < n; i++) {
if (a[i] > a[i + 1]) {
flag = true;
int t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
}
}
}
}