In the last lesson, you saw why sorting matters and how sorting algorithms are compared. Now it's time to learn our first one.
Bubble Sort is the simplest sorting algorithm to understand, which makes it the perfect place to start. Every algorithm in this chapter sorts the same array, [5, 1, 4, 2, 8], so you can compare how each one works.
By the end of this lesson, you will understand:
- How Bubble Sort works
- How to trace it by hand, one step at a time
- How to write it in code
- Its Big-O, and when it is (and isn't) a good choice
What Is Bubble Sort?
Bubble Sort repeatedly walks through the array, compares each pair of neighbours, and swaps them if they are in the wrong order.
After each full walk through the array, called a pass, the largest remaining item has "bubbled up" to its correct place at the end, just like a bubble rising to the top of water. That's where the name comes from.
Watch it happen below. Each bubble's size shows its value. Press Play, or use the arrows to go one step at a time. Then try Reversed and Sorted to see the worst and best cases you'll meet later in this lesson.
The Line of Students Analogy
Imagine students standing in a line, and you want to arrange them from shortest to tallest. You are only allowed to look at two neighbours at a time.
1. Compare Two Neighbours
Start at the left. Look at the first two students. If the left one is taller, ask them to swap places.
2. Move One Step Right
Now compare the 2nd and 3rd students, swap if needed, and keep going until you reach the end of the line.
3. The Tallest Reaches the End
By the time you reach the end, the tallest student has been swapped all the way to the last spot. They are now in their final place, so you never need to check them again.
4. Repeat
Go back to the start and repeat for everyone except the students already in place. When you get through a whole pass without a single swap, the line is sorted, and you can stop.
Tracing It by Hand
Let's sort [5, 1, 4, 2, 8] and watch every step.
Pass 1
| Compare | Wrong order? | Array after |
|---|---|---|
| 5 and 1 | Yes, swap | [1, 5, 4, 2, 8] |
| 5 and 4 | Yes, swap | [1, 4, 5, 2, 8] |
| 5 and 2 | Yes, swap | [1, 4, 2, 5, 8] |
| 5 and 8 | No | [1, 4, 2, 5, 8] |
8, the largest, is now in its final place.
Pass 2
| Compare | Wrong order? | Array after |
|---|---|---|
| 1 and 4 | No | [1, 4, 2, 5, 8] |
| 4 and 2 | Yes, swap | [1, 2, 4, 5, 8] |
| 4 and 5 | No | [1, 2, 4, 5, 8] |
We stop one item earlier this time, because 8 is already in place. 5 is now in its final place too.
Pass 3
| Compare | Wrong order? | Array after |
|---|---|---|
| 1 and 2 | No | [1, 2, 4, 5, 8] |
| 2 and 4 | No | [1, 2, 4, 5, 8] |
No swaps at all in this pass, which means everything is already in order. We can stop early.
The result is [1, 2, 4, 5, 8], done in 9 comparisons. Without the early stop, it would have taken 10.
Bubble Sort in Code
import java.util.Arrays;
public class Main {
static void bubbleSort(int[] a) {
int n = a.length;
for (int i = 0; i < n - 1; i++) {
boolean swapped = false;
for (int j = 0; j < n - 1 - i; j++) { // the last i items are already in place
if (a[j] > a[j + 1]) { // neighbours in the wrong order?
int temp = a[j]; // swap them
a[j] = a[j + 1];
a[j + 1] = temp;
swapped = true;
}
}
if (!swapped) {
break; // no swaps: already sorted, stop early
}
}
}
public static void main(String[] args) {
int[] marks = {5, 1, 4, 2, 8};
bubbleSort(marks);
System.out.println(Arrays.toString(marks)); // [1, 2, 4, 5, 8]
}
}Let's connect the code to the trace:
- The outer loop (
i) is one pass. - The inner loop (
j) compares each pair of neighbours,a[j]anda[j + 1]. - The inner loop stops at
n - 1 - ibecause afteripasses, the lastiitems are already in their final place. That is why Pass 2 compared one fewer pair than Pass 1. swappedremembers whether anything moved. If a whole pass makes no swaps,breakstops early.
Watch It Run
Here is the Java version sorting the same array, [5, 1, 4, 2, 8], one line at a time. Keep an eye on three things:
- The highlighted line on the left shows which line of code is running.
tempbriefly holds a value during each swap.- The "fixed" boxes on the right are the sorted part. Notice how
swappedstaysfalsein Pass 3, so the sort stops early.
How Fast Is Bubble Sort?
Using what you learned about Big-O:
| Case | Example | Time | Why |
|---|---|---|---|
| Best | Already sorted: [1, 2, 3, 4, 5] | O(n) | One pass, no swaps, stop early |
| Average | Random order | O(n²) | Many passes, each comparing many pairs |
| Worst | Reverse order: [5, 4, 3, 2, 1] | O(n²) | Every pair swaps on every pass |
| Extra memory | Any | O(1) | Sorts in place, with just one temp variable |
The nested loop gives it away: a loop inside a loop is O(n²). The best case is only O(n)because of the early stop. Without the swapped check, Bubble Sort is O(n²) even on an already sorted array.
Bubble Sort is "stable". If two items are equal, they keep their original order. That's because it only swaps when the left item is strictly greater (
>), never when they are equal.
Common Mistakes
1. Going One Step Too Far
Writing the inner loop as j < n - i instead of j < n - 1 - i makes it compare the last item with a[j + 1], which is past the end of the array. Java and Python will stop with an error, and in C it is undefined behaviour. (Look back at "What If You Go Past the End?" in the first lesson of this chapter.)
2. Using >= Instead of >
Swapping equal items does extra, useless work, and it breaks stability: equal items lose their original order.
3. Forgetting to Reset swapped
swapped must go back to false at the start of every pass. If you only set it once at the top, the early stop never triggers after the first swap.
When Should You Use Bubble Sort?
Good for:
- Learning how sorting works. It is the easiest to understand and trace
- Very small arrays, or arrays that are already almost sorted
Not good for:
- Large amounts of data. With 10,000 items, Bubble Sort can need around 50 million comparisons
In real projects, you almost always use the language's built-in sort, like Java's Arrays.sort(), Python's sorted() or JavaScript's .sort(), which are O(n log n). Learning Bubble Sort first makes those faster algorithms much easier to understand when we reach them.
In the next lesson, we will learn Selection Sort, which needs far fewer swaps.
Remember This
If you remember only one thing from this lesson, remember:
Bubble Sort compares neighbours and swaps them when they're in the wrong order. Each pass moves the largest item to the end. It is O(n²), simple to learn, but too slow for large data.