Bubble sort in JavaScript
Intermediate · 3 min read
Bubble sort is the classic first sorting algorithm. You would never ship it in a real app, because JavaScript's own sort is much faster. But it is short, easy to picture, and it teaches the ideas behind every other sort: comparing, swapping and repeating until nothing is out of place.
In this tutorial you will sort [6, 4, 0, 3, -2, 1] into [-2, 0, 1, 3, 4, 6] by swapping neighbors. Then you will add two small improvements that make it stop as soon as it can. You need to know for loops and array indexes.
The idea
Walk along the list and look at each pair of neighbors. If the left one is bigger, swap them. One walk from start to end is called a pass.
After one pass, the biggest number has "bubbled" all the way to the end, like a bubble rising in water. Do another pass, and the second biggest reaches the second-to-last spot. Keep going until the whole list is in order.
Swapping two items
JavaScript can swap two array items in one line with destructuring: build a pair on the right, and unpack it on the left in the other order.
const pair = [6, 4];
[pair[0], pair[1]] = [pair[1], pair[0]];
console.log(pair); // [ 4, 6 ]
Here is the exercise. Try it yourself first if you like, then read on and we will build it.
6 Bubble sort
fairSort [6, 4, 0, 3, -2, 1] into [-2, 0, 1, 3, 4, 6] by repeatedly swapping neighbours that are in the wrong order.
Stuck? Three hints, smallest first
- 1. Each full pass moves the largest remaining value to the end, so the tail is already sorted.
- 2. Stop early when a pass makes no swaps: the list is sorted and further passes are wasted work.
- 3. Shrink the inner loop by one each pass, since the end is already correct.
Step 1: one pass
Start with a single pass over a copy of the list. slice() with nothing in the brackets copies an array, so the caller's array stays as it was:
const values = [6, 4, 0, 3, -2, 1].slice();
for (let i = 0; i < values.length - 1; i++) {
if (values[i] > values[i + 1]) {
[values[i], values[i + 1]] = [values[i + 1], values[i]];
}
}
console.log(values.join(' ')); // 4 0 3 -2 1 6
The loop stops one before the end because it compares i with i + 1. The 6 has reached the last spot, but the rest is still mixed up.
Step 2: repeat the pass
Wrap the pass in an outer loop. The answer counts a variable end down from the last index, and the inner loop stops at end:
function bubbleSort(input) {
const values = input.slice();
for (let end = values.length - 1; end > 0; end--) {
for (let i = 0; i < end; i++) {
if (values[i] > values[i + 1]) {
[values[i], values[i + 1]] = [values[i + 1], values[i]];
}
}
}
return values;
}
console.log(bubbleSort([6, 4, 0, 3, -2, 1])); // [ -2, 0, 1, 3, 4, 6 ]
Why shrink end? After the first pass the biggest value is at the end for good, so there is no point comparing it again. Each pass can stop one place earlier than the last.
Step 3: stop early when nothing moved
If a whole pass makes no swaps, the list is already sorted and the remaining passes would do nothing. Keep a swapped flag, and count the passes so you can see the effect:
function bubbleSort(input) {
const values = input.slice();
let passes = 0;
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]) {
[values[i], values[i + 1]] = [values[i + 1], values[i]];
swapped = true;
}
}
passes++;
if (!swapped) break;
}
return { values, passes };
}
console.log(bubbleSort([1, 2, 3, 4, 5]).passes); // 1
console.log(bubbleSort([5, 4, 3, 2, 1]).passes); // 4
break leaves the outer loop at once. A sorted list now takes one pass. A reversed list still needs four, the most a five-item list can need.
The function now returns an object with both the sorted values and the pass count. The answer adds a tiny wrapper for when you only want the values:
const sort = (input) => bubbleSort(input).values;
const sample = [6, 4, 0, 3, -2, 1];
console.log(sort(sample)); // [ -2, 0, 1, 3, 4, 6 ]
console.log(sample); // [ 6, 4, 0, 3, -2, 1 ]
The second line proves the input was not changed, thanks to the slice() copy.
Step 4: compare with the built-in sort
The built-in sort needs a compare function for numbers, (a, b) => a - b. Both should agree:
console.log(sort([10, 9, 100, 1])); // [ 1, 9, 10, 100 ]
console.log([10, 9, 100, 1].slice().sort((a, b) => a - b)); // [ 1, 9, 10, 100 ]
The full solution
The panel has the finished bubbleSort with both improvements. It sorts the sample, shows the input is unchanged, and prints the pass counts for a sorted and a reversed list. Press Run to see them.
function bubbleSort(input) {
const values = input.slice(); // do not modify the caller's array
let passes = 0;
for (let end = values.length - 1; end > 0; end--) {
let swapped = false;
for (let i = 0; i < end; i++) { // end shrinks: the tail is done
if (values[i] > values[i + 1]) {
[values[i], values[i + 1]] = [values[i + 1], values[i]];
swapped = true;
}
}
passes++;
if (!swapped) break; // already sorted, stop
}
return { values, passes };
}
const sort = (input) => bubbleSort(input).values;
const sample = [6, 4, 0, 3, -2, 1];
console.log('input :', sample);
console.log('sorted:', sort(sample));
console.log('input afterwards:', sample, '<- unchanged');
console.log('--- the early exit earns its place ---');
console.log('passes for already-sorted [1,2,3,4,5]:', bubbleSort([1, 2, 3, 4, 5]).passes);
console.log('passes for reversed [5,4,3,2,1]:', bubbleSort([5, 4, 3, 2, 1]).passes);
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the sample", sort(sample), [-2, 0, 1, 3, 4, 6]);
test('the input is not modified', sample, [6, 4, 0, 3, -2, 1]);
test('an empty array', sort([]), []);
test('one element', sort([1]), [1]);
test('already sorted stays sorted', sort([1, 2, 3]), [1, 2, 3]);
test('reversed gets fixed', sort([3, 2, 1]), [1, 2, 3]);
test('duplicates are kept', sort([2, 1, 2, 1]), [1, 1, 2, 2]);
test('it agrees with a numeric sort()', sort([10, 9, 100, 1]), [10, 9, 100, 1].slice().sort((a, b) => a - b));
test('a sorted list needs only one pass', bubbleSort([1, 2, 3, 4, 5]).passes, 1);
test('a reversed list needs the full n-1', bubbleSort([5, 4, 3, 2, 1]).passes, 4);
test('so the early exit really does save work', bubbleSort([1, 2, 3, 4, 5]).passes < bubbleSort([5, 4, 3, 2, 1]).passes, true);
Bubble sort is O(n²) and you should not ship it, but the two optimisations are worth writing once. Shrinking the inner loop each pass is correct because a full pass guarantees the largest remaining value has reached the end. And the swapped flag turns an already-sorted input into a single pass instead of n−1 — the assertions compare 1 against 4 to prove it. That makes it O(n) on sorted data, which is the one thing bubble sort is genuinely good at.
Common mistakes
- Looping
iup tovalues.length. Thenvalues[i + 1]reads past the end and compares withundefined. Stop atend. - Sorting the caller's array. Without
slice(), the function changes the array you passed in. - Leaving out the
swappedflag. The sort still works, but an already sorted list does every pass for nothing.
Try it yourself
- Change one character so the sort goes from biggest to smallest.
- Print
values.join(' ')at the end of every pass to watch the big numbers bubble to the right. - Count the swaps as well as the passes. How many does
[6, 4, 0, 3, -2, 1]need?