Bubble Sort
Bubble Sort repeatedly compares adjacent elements and “bubbles” the larger (or smaller) one toward the end, pass by pass, until fully sorted.
Click "Step forward" to watch the algorithm state change.
- Scan adjacent pairs; swap if out of order.
- Each pass bubbles the max (or min) of the unsorted part to the end.
- Repeat for passes until sorted.
Pseudo-code:
for i = 0 to n-2:
for j = 0 to n-2-i:
if A[j] > A[j+1]:
swap(A[j], A[j+1])
#include <stdbool.h>
void BubbleSort(int A[], int n) {
for (int i = 0; i < n - 1; i++) {
bool flag = false; // whether a swap happened in this pass
for (int j = 0; j < n - 1 - i; j++) {
if (A[j] > A[j + 1]) {
int tmp = A[j];
A[j] = A[j + 1];
A[j + 1] = tmp;
flag = true;
}
}
if (!flag) break; // no swap in this pass, so it is already sorted
}
}
Optimization Notes
The flag flag records whether any swap happened during the pass: if a pass performs no swap at all, the sequence is already sorted and the algorithm can stop early. This makes the best case (an already sorted array) take a single pass and comparisons, reaching .
- Best: (already sorted, with early-exit optimization)
- Worst/avg:
- Space:
- Stability: stable
Exercise 1
Sort with bubble sort; show each pass.
Approach: Each pass “bubbles” the largest element to the end of the array.
Steps:
- Initial: [4, 3, 2, 1]
- Pass 1: [3, 2, 1, 4]
- Pass 2: [2, 1, 3, 4]
- Pass 3: [1, 2, 3, 4]
Answer: As shown above; after every pass the largest element sits in its final position.
Exercise 2
What are the time and space complexities of bubble sort?
Approach: Consider the time complexity and the extra space.
Steps:
- Time complexity
- Space complexity
Answer: Time , space .
