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
- What is Sorting? — Sorting means arranging elements in a specific order — usually smallest to largest (ascending) or largest to smallest (descending). Sorting is one of the most fundamental operations in computer science.
- How Bubble Sort Works — Bubble sort repeatedly walks through the array, comparing adjacent (neighboring) elements. If they are in the wrong order, it swaps them. After each full pass, the largest unsorted element 'bubbles' to its correct position at the end.
- Step-by-Step Example — Array: [5, 3, 8, 1]. Pass 1: compare 5,3 -> swap -> [3,5,8,1]; compare 5,8 -> ok; compare 8,1 -> swap -> [3,5,1,8]. Now 8 is in place! Pass 2: [3,5,1,8] -> [3,1,5,8]. Pass 3: [1,3,5,8]. Done!
- The Swap Operation — To swap two variables in C++, we use a temporary variable: int temp = a; a = b; b = temp; Or we can use the built-in swap(a, b) function which does the same thing. Swapping is the heart of bubble sort.
- How Many Passes? — For an array of n elements, we need at most n-1 passes. In each pass, we compare adjacent elements and swap if needed. After pass k, the k-th largest element is in its final position.
- Time Complexity Hint — Bubble sort compares every pair in each pass, and does up to n-1 passes. That means roughly n * n comparisons in the worst case. We write this as O(n^2). For 1000 elements, that is about 1 million comparisons — slow for big data, but fine for learning!
- Optimization: Early Stop — If we go through a complete pass without making any swaps, the array is already sorted! We can add a boolean flag to check this and stop early. This makes bubble sort faster when the data is nearly sorted.
- When to Use Bubble Sort — In competitive programming, you almost never use bubble sort for actual sorting (C++ sort() is much faster). But understanding bubble sort teaches you about comparisons, swaps, and algorithm analysis. Some CP problems specifically ask about bubble sort or count swaps.
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. 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. 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. 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. 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. 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. swap(arr[j], arr[j + 1]); — C++ built-in swap function exchanges the two values. This is cleaner than using a temporary variable.
- 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
- Bubble Sort Visualized (YouTube)
- Sorting Algorithms for Beginners (GeeksforGeeks)
- Sort the Array (Codeforces)