Lesson 24 of 50 intermediate

Bubble Sort — The Swapping Dance

The simplest sorting algorithm you will ever learn

Open interactive version (quiz + challenge)

Real-world analogy

Imagine sorting students by height in a line. You start at the beginning, compare the first two students — if the taller one is in front, they swap. Then compare positions 2 and 3, then 3 and 4, and so on. After one pass, the tallest student 'bubbles up' to the end. Repeat until everyone is in order!

What is it?

Bubble sort is the simplest sorting algorithm. It works by repeatedly stepping through the array, comparing each pair of adjacent elements, and swapping them if they are in the wrong order. The largest elements gradually 'bubble up' to the end of the array, just like air bubbles rising to the surface of water.

Real-world relevance

While bubble sort is too slow for large datasets, the concept of comparing neighbors and swapping is used everywhere. Card players naturally use a form of bubble sort when arranging their hand. Teachers sometimes line up students by height using the 'compare two neighbors' approach. Understanding simple algorithms helps you appreciate why faster algorithms exist.

Key points

Code example

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    int n;
    cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    // Bubble Sort
    for (int i = 0; i < n - 1; i++) {
        bool swapped = false;
        for (int j = 0; j < n - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                swapped = true;
            }
        }
        if (!swapped) break; // Array is already sorted!
    }

    // Print sorted array
    for (int i = 0; i < n; i++) {
        cout << arr[i];
        if (i < n - 1) cout << " ";
    }
    cout << "\n";

    return 0;
}

Line-by-line walkthrough

  1. 1. vector arr(n); — we create a vector (dynamic array) of size n to hold our numbers. Vectors are super handy in C++ because they manage memory for us.
  2. 2. for (int i = 0; i < n - 1; i++) — the outer loop runs n-1 times. Each pass places one more element in its final position. After n-1 passes, everything is sorted.
  3. 3. bool swapped = false; — this flag tracks whether we made any swaps in this pass. If we complete a pass with no swaps, the array is already sorted and we can stop early.
  4. 4. for (int j = 0; j < n - 1 - i; j++) — the inner loop compares adjacent elements. We use n-1-i because after i passes, the last i elements are already in their correct positions, so we do not need to check them again.
  5. 5. if (arr[j] > arr[j + 1]) — we compare two neighbors. If the left one is bigger than the right one, they are in the wrong order for ascending sort.
  6. 6. swap(arr[j], arr[j + 1]); — C++ built-in swap function exchanges the two values. This is cleaner than using a temporary variable.
  7. 7. if (!swapped) break; — if no swaps happened in a complete pass, the array is sorted. This optimization can save a lot of time on nearly-sorted data.

Spot the bug

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++) cin >> arr[i];

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }

    for (int i = 0; i < n; i++) cout << arr[i] << " ";
    return 0;
}
Need a hint?
Look at the inner loop bounds. When j equals n-1, what is j+1? Does that index exist in the array?
Show answer
There are two bugs! First, the inner loop goes 'j < n' which means when j = n-1, we access arr[n] which is out of bounds — undefined behavior! It should be 'j < n - 1 - i'. Second, the outer loop should be 'i < n - 1' (we only need n-1 passes). Fix: change to 'for (int i = 0; i < n - 1; i++)' and 'for (int j = 0; j < n - 1 - i; j++)'.

Explain like I'm 5

Imagine you have a line of toy blocks with numbers on them, and you want to put them in order from smallest to biggest. You look at the first two blocks — if the bigger one is first, you swap them. Then look at the next two, swap if needed, and keep going to the end. After going through the whole line once, the biggest block is at the end. Now do it again (ignoring the last block since it is in place). Keep doing this until no more swaps are needed. That is bubble sort!

Fun fact

Bubble sort was one of the first sorting algorithms ever analyzed by computer scientists. Despite being slow, it has a special place in computing history. Barack Obama, when asked in an interview what the most efficient way to sort a million integers is, jokingly said 'I don't think the bubble sort is the way to go.' He was right — but it is a great way to start learning!

Hands-on challenge

Write a bubble sort program that not only sorts the array but also prints the array after EACH pass so you can see the sorting happen step by step. Also count and print the total number of swaps made. Test with input: 5 elements [4, 2, 5, 1, 3].

More resources

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero