Lesson 9 of 19
Bubble sort
Line up number cards from smallest to largest. Compare neighbors and swap them when the left one is bigger. A pass moves the largest remaining card to the right.
A pass can prove the array is sorted
The largest remaining value moves right whenever a smaller neighbor follows it, so each full pass puts one more value in its final position. If a whole pass makes zero swaps, every adjacent pair is already in order and the algorithm can stop early.
Work through an example
Start with [2, 1, 3, 4]. How many swaps happen? Why does the algorithm still need a second pass?
Step-by-step solution
- Compare 2 and 1 and swap them. The remaining pairs, 2 and 3 then 3 and 4, are already in order.
- The array is now [1, 2, 3, 4]. Because the first pass made a swap, the early-stop rule has yet to establish that everything is in order.
- The second pass checks 1 against 2 and 2 against 3. It makes zero swaps and stops. Total work was five comparisons and one swap.
JavaScript example
function bubbleSort(values) {
for (let end = values.length - 1; end > 0; end--) {
let swapped = false;
for (let i = 0; i < end; i++) {
if (values[i] <= values[i + 1]) continue;
[values[i], values[i + 1]] = [values[i + 1], values[i]];
swapped = true;
}
if (!swapped) break;
}
return values;
}
bubbleSort([2, 1, 3, 4]); // [1, 2, 3, 4]DSA compiler
Try it yourself
Finish the animation to unlock this question.
After one full left-to-right pass over [3, 2, 1], what is the order?
Related exercise · Mergesort · See this stage of the beginner path