Bubble Sort in Java — Explained Simply with Code
Table of Contents
Imagine you're handed a shuffled deck of 5 playing cards and told to sort them — but there's a rule: you can only compare two cards next to each other at a time, and swap them if they're in the wrong order. You keep walking down the line, swapping out-of-order pairs, again and again, until one full pass goes by with no swaps at all. That's it — that's Bubble Sort.
It's not the fastest algorithm you'll ever write. But it's the one that teaches you how sorting actually works under the hood — and once it clicks, every other sorting algorithm on this blog will make a lot more sense.
Why "Bubble" Sort?
Picture the numbers in your array as bubbles in a glass of soda. Every time a bigger bubble is below a smaller one, they swap places — so with each pass, the biggest remaining "bubble" floats up to its correct spot at the end of the list. Do enough passes, and eventually every bubble has floated to exactly where it belongs.
You'll sometimes see this called a "sinking sort" too — same idea, just described from the other direction: the biggest values sink to the bottom (end) of the array.
Let's Walk Through an Example
Take the array [5, 1, 4, 2, 8]. Here's what the first full pass
looks like, one comparison at a time:
- Compare
5and1→ out of order → swap →[1, 5, 4, 2, 8] - Compare
5and4→ out of order → swap →[1, 4, 5, 2, 8] - Compare
5and2→ out of order → swap →[1, 4, 2, 5, 8] - Compare
5and8→ already in order → no swap
Notice what happened: 8, the largest number, "bubbled" all the
way to the end in a single pass. The algorithm now repeats this process on the
remaining unsorted portion, ignoring the last (already correct) element each
time — until nothing needs swapping anymore.
Turning That Into Code
Here's the logic above, translated line-by-line into Java. Read the comments — they map directly to the walkthrough steps you just saw:
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
// Keep making passes over the array
for (int i = 0; i < n - 1; i++) {
swapped = false;
// Compare each pair of neighbors, ignoring the sorted tail
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Out of order — swap them
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If we made a full pass with zero swaps, the array is sorted —
// no point continuing, so we stop early.
if (!swapped) break;
}
}
public static void main(String[] args) {
int[] arr = {5, 1, 4, 2, 8};
bubbleSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
// Output: 1 2 4 5 8
}
}
Same logic, in Python — useful if you're more comfortable there, or want to compare syntax side by side:
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break # already sorted — no need to keep going
return arr
print(bubble_sort([5, 1, 4, 2, 8]))
# Output: [1, 2, 4, 5, 8]
The swapped flag is doing more work than it looks like. Without
it, Bubble Sort always runs the full O(n²) number of comparisons — even on an
already-sorted array. With it, a sorted array finishes in a single O(n) pass.
That one boolean is the difference between "textbook" Bubble Sort and a
slightly-smarter version of it.
How Slow Is It, Really?
This is the part interviewers actually care about — not whether you can write the loop, but whether you understand its cost:
Best case: O(n) — the array is already sorted, so the swapped
flag lets it exit after one pass.
Average case: O(n²) — most pairs need at least one comparison.
Worst case: O(n²) — a reverse-sorted array forces every possible swap.
Space: O(1) — it sorts in place, no extra memory needed.
For context: sorting 10 items takes at most ~100 comparisons. Sorting 10,000 items takes up to 100 million. That's why you'll never see Bubble Sort used on anything but small or teaching examples — real systems reach for Merge Sort or Quick Sort instead, which we'll cover next in this series.
Questions You Might Get Asked About This
- Why is Bubble Sort considered a stable sort? (Hint: equal elements never get swapped past each other.)
- What does the
swappedflag actually optimize, and why doesn't basic Bubble Sort include it by default? - How would you flip this to sort in descending order? (One symbol changes.)
- If Bubble Sort is so slow, why do we still teach it?
The Takeaway
Bubble Sort won't win any speed contests, but it's the clearest possible introduction to a core idea: repeatedly compare and fix small pieces until the whole thing is correct. That exact idea — break it down, fix a little at a time — is the foundation for almost every algorithm you'll learn after this one. Next up: Selection Sort, which takes a slightly different approach to the same problem.
Comments
Post a Comment