A PE teacher wants a row of students lined up from shortest to tallest. There's one rule: two students standing next to each other may swap places if the one on the left is taller. The teacher walks from the left end to the right end, and swaps every pair that's in the wrong order. By the time the teacher reaches the right end, the tallest student is sure to be standing at the far right.
The teacher's method is bubble sort. Bubble sort compares two numbers that sit side by side (neighbours), then swaps them if they're in the wrong order. In the row of students, each student is one number in the array, and the student's height is that number's value. One run from left to right is called one pass. On every pass, the biggest number that isn't in place yet gets pushed to the right, into its place, like a bubble rising to the surface of water.
How it works
Sort [64, 34, 25, 12, 22, 11, 90] from small to big. On pass 1, 64 is compared with its neighbour, 34. 64 is bigger, so the two swap. Then 64 is compared with 25 and swaps again, and so on. In the end 64 meets 90, which is bigger, so 64 stops just before 90. This table shows the array after each pass:
| Pass | What happens | Array afterwards |
|---|---|---|
| 1 | 64 is swapped right until it sits before 90 | [34, 25, 12, 22, 11, 64, 90] |
| 2 | 34 is swapped right until it sits before 64 | [25, 12, 22, 11, 34, 64, 90] |
| 3 | 25 is swapped right until it sits before 34 | [12, 22, 11, 25, 34, 64, 90] |
| 4 | 22 swaps with 11 | [12, 11, 22, 25, 34, 64, 90] |
| 5 | 12 swaps with 11 | [11, 12, 22, 25, 34, 64, 90] |
| 6 | nothing swaps | [11, 12, 22, 25, 34, 64, 90] |
After each pass, the right end of the array is sorted and doesn't need to be touched again. Here is bubble sort in JavaScript:
function bubbleSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; // swap
}
}
}
return arr;
}
console.log(bubbleSort([64, 34, 25, 12, 22, 11, 90]).join(",")); // 11,12,22,25,34,64,90
- This code has a loop inside a loop. The outer loop (
i) counts the passes. 7 numbers need at most 6 passes, so its condition isi < arr.length - 1. - The inner loop (
j) compares each pair of neighbours,arr[j]andarr[j + 1]. Its limit isarr.length - 1 - i, because afteripasses, theirightmost numbers are already in place. if (arr[j] > arr[j + 1]): swap only when the left one is bigger.[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]swaps two items of the array in one line. A longer way uses a helper variable:const temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp;.return arris written after both loops. Bubble sort changes the original array, then returns that same array..join(",")joins the array's items into one piece of text, separated by commas with no spaces.
Stopping early
If a pass swaps nothing, every pair of neighbours is already in order, so bubble sort can stop. You do that with a swapped flag, a true/false variable that records whether this pass has swapped anything:
- At the start of each pass, write
let swapped = false;. - When you swap, also write
swapped = true;. - After the inner loop ends, write
if (!swapped) break;.breakstops the outer loop.
Think about it first: the array is already sorted, [1, 2, 3, 4, 5]. Does bubble sort still repeat every pass to the end? Without swapped, yes: the array is still checked pass after pass. With swapped, one pass is enough, then it stops.
How slow it is
The amount of data is called n. 7 numbers take 6 + 5 + 4 + 3 + 2 + 1 = 21 comparisons: 6 on the first pass, 5 on the second, and so on. A loop inside a loop like this is written O(n²): double the data, and the time is roughly four times as long. 100 numbers take 4,950 comparisons, and 200 numbers already take 19,900.
- Average and worst case (shuffled data, or data in reverse order from big to small): O(n²).
- Best case: the data is already sorted and the code uses
swapped. One pass is enough, n - 1 comparisons, so O(n): double the data, double the time. Withoutswapped, the best case is still O(n²).
Bubble sort is easy to understand, but too slow for big data. For everyday work, JavaScript already has arr.sort((a, b) => a - b), which sorts numbers from small to big.
⚠️ Why is the result undefined, or only half sorted?
- Forgetting
return arr. The function returnsundefined, and the.join(",")after it causes an error. return arrinside a loop. In the outer loop, the function stops after the first pass, so the result is still[34, 25, 12, 22, 11, 64, 90]. Putreturn arrafter both loops have finished.- A number typed in directly.
j < 6only fits 7 numbers. Usearr.lengthso the code works for an array of any length.
💡 Bubble sort is stable. Stable means that items with the same value stay in their original order. In bubble sort, two equal numbers are never swapped, because the condition is
>(bigger than), not>=(bigger than or equal to). That's useful when sorting things like a list of students by score: two students with the same score stay in the order they had in the first list.
TL;DR: Bubble sort sorts an array by comparing neighbours (two numbers side by side), arr[j] and arr[j + 1], then swapping them if the left one is bigger. One run from left to right is called one pass. Every pass pushes the biggest remaining number to the right, so after i passes, the loop that compares neighbours only needs to run to arr.length - 1 - i. Don't forget return arr after all the passes have finished. A swapped flag, which records whether anything was swapped, stops bubble sort as soon as a pass swaps nothing. It's O(n²), and O(n) on already sorted data if you use swapped.
⚡ Swap neighbours in the wrong order
Write:
function bubbleSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; // swap
}
}
}
return arr;
}
Meaning: Bubble sort compares the neighbours (two numbers side by side) arr[j] and arr[j + 1], and swaps them if the left one is bigger. The outer loop (i) counts the passes, where a pass is one run from left to right. Every pass pushes the biggest remaining number to the right, so the inner loop (j) only needs to run to arr.length - 1 - i.
⚡ return arr after both loops
Meaning: If you forget return arr, the function returns undefined. If you put return arr inside a loop, the function stops too early, and the array is only partly sorted.
⚡ Stop early with swapped
Guess first: a swapped flag records whether a pass swapped anything, and bubble sort stops as soon as a pass swaps nothing. The array is already sorted, [1, 2, 3, 4, 5]. How many passes does bubble sort need?
Just one. Nothing gets swapped, so bubble sort stops. Without swapped, the array is still checked pass after pass.
Meaning: A loop inside a loop makes bubble sort O(n²): 100 numbers take 4,950 comparisons. If the data is already sorted and the code uses swapped, its best case is O(n).