Bubble Sort

Idea

Bubble Sort repeatedly compares adjacent elements and “bubbles” the larger (or smaller) one toward the end, pass by pass, until fully sorted.

Bubble sort

Click "Step forward" to watch the algorithm state change.

Algorithm

  1. Scan adjacent pairs; swap if out of order.
  2. Each pass bubbles the max (or min) of the unsorted part to the end.
  3. Repeat for n−1n-1 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])

Code Implementation

#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 n−1n-1 comparisons, reaching O(n)O(n).

Complexity

  • Best: O(n)O(n) (already sorted, with early-exit optimization)
  • Worst/avg: O(n2)O(n^2)
  • Space: O(1)O(1)
  • Stability: stable

Exercises

Exercise 1

Sort A=[4,3,2,1]A = [4, 3, 2, 1] with bubble sort; show each pass.

Bubble SortSwapPass

Approach: Each pass “bubbles” the largest element to the end of the array.

Steps:

  1. Initial: [4, 3, 2, 1]
  2. Pass 1: [3, 2, 1, 4]
  3. Pass 2: [2, 1, 3, 4]
  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?

Bubble SortTime ComplexitySpace Complexity

Approach: Consider the time complexity and the extra space.

Steps:

  1. Time complexity O(n2)O(n^2)
  2. Space complexity O(1)O(1)

Answer: Time O(n2)O(n^2), space O(1)O(1).

Found an issue with this content?

Tell us what could be improved.