Bubble sort in descending order in JavaScript
Intermediate · 3 min read
Bubble sort is often the first sorting method people learn, because you can do it by hand with a row of playing cards. Look at two neighbors, swap them if they are in the wrong order, and move along. Repeat until nothing needs swapping. Big values "bubble" to one end, which is where the name comes from.
In this tutorial you will write bubbleSort(input, compare). The exercise's sample output puts the largest number first, so the target is descending order. Instead of writing one function for each direction, you will pass the direction in as a function. You need to know arrays, loops and functions.
How bubble sort works
Take [3, 1, 2] and sort it from small to large:
pass 1: [3, 1, 2] 3 > 1, swap -> [1, 3, 2]
[1, 3, 2] 3 > 2, swap -> [1, 2, 3]
pass 2: [1, 2, 3] 1 < 2, fine -> no swaps, so it is sorted
After each pass, the largest value left has reached its place at the end. So each pass can stop one position earlier than the last.
Compare functions
A compare function takes two values and returns a number that says which comes first. A positive number means "these two are in the wrong order". Zero or negative means "leave them".
const ascending = (a, b) => a - b;
const descending = (a, b) => b - a;
console.log(ascending(5, 2)); // 3: positive, so 5 should go after 2
console.log(descending(5, 2)); // -3: leave them, 5 stays first
The built-in sort uses the same rule, so anything you learn here carries over.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
24 Bubble sort
fairSort by swapping neighbours. The expected output for its sample is descending, so read the data rather than the name.
Stuck? Three hints, smallest first
- 1. Compare the sample output with the sample input: the largest value comes first.
- 2. A comparator parameter lets one function do both directions.
- 3. Stop early when a pass makes no swaps.
Step 1: swap two neighbors
JavaScript can swap two array items in one line using destructuring: unpacking an array into separate places.
const values = [3, 1];
[values[0], values[1]] = [values[1], values[0]];
console.log(values); // [1, 3]
The right side builds a new pair in swapped order, and the left side writes it back.
Step 2: one pass
Walk along the array once, comparing each item with the next one:
function onePass(values) {
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]];
}
}
return values;
}
console.log(onePass([5, 1, 4, 2])); // [1, 4, 2, 5]
The largest value, 5, has bubbled to the end. The rest are not sorted yet, so one pass is not enough.
Step 3: repeat, and shrink the end
Put the pass inside another loop. end marks the last position that still needs checking, and it moves one step left after every pass:
function sortUp(input) {
const values = [...input];
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;
}
const nums = [5, 1, 4, 2];
console.log(sortUp(nums)); // [1, 2, 4, 5]
console.log(nums); // [5, 1, 4, 2]: unchanged
[...input] makes a copy first. Sorting is done on the copy, so the caller's array keeps its order. That is a kind thing for a function to do.
Step 4: pass the direction in
Swap values[i] > values[i + 1] for compare(values[i], values[i + 1]) > 0. Now the caller decides the order. Giving compare a default makes ascending the normal case:
function bubbleSort(input, compare = (a, b) => a - b) {
const values = [...input];
for (let end = values.length - 1; end > 0; end--) {
for (let i = 0; i < end; i++) {
if (compare(values[i], values[i + 1]) > 0) {
[values[i], values[i + 1]] = [values[i + 1], values[i]];
}
}
}
return values;
}
console.log(bubbleSort([12, 345, 4, 546])); // [4, 12, 345, 546]
console.log(bubbleSort([12, 345, 4, 546], (x, y) => y - x)); // [546, 345, 12, 4]
console.log(bubbleSort(['c', 'a', 'b'], (a, b) => a.localeCompare(b, 'en'))); // ['a', 'b', 'c']
One body now sorts numbers both ways, and even text. localeCompare is the string method that compares words in dictionary order.
Step 5: stop early when nothing moves
If a whole pass makes no swaps, the array is already sorted and the rest of the passes would be wasted. A swapped flag tracks that. The answer also counts passes and returns them next to the sorted values:
function bubbleSortCounted(input, compare = (a, b) => a - b) {
const values = [...input];
let passes = 0;
for (let end = values.length - 1; end > 0; end--) {
let swapped = false;
for (let i = 0; i < end; i++) {
if (compare(values[i], values[i + 1]) > 0) {
[values[i], values[i + 1]] = [values[i + 1], values[i]];
swapped = true;
}
}
passes++;
if (!swapped) break;
}
return { values, passes };
}
console.log(bubbleSortCounted([1, 2, 3, 4, 5]).passes); // 1
console.log(bubbleSortCounted([5, 4, 3, 2, 1]).passes); // 4
A sorted list costs one pass. A list in reverse order still needs n - 1 passes. break leaves the outer loop at once. In the full solution, this version takes the name bubbleSort.
The full solution
The panel has bubbleSort with the early exit, plus small ascending and descending helpers built on it. It sorts the 15-number sample both ways, shows the input is unchanged, and prints the pass counts. Press Run to see the output.
/* One function, either direction, by taking a comparator. The sample
output is descending, which is what the data shows. */
function bubbleSort(input, compare = (a, b) => a - b) {
const values = [...input]; // never reorder 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++) {
if (compare(values[i], values[i + 1]) > 0) {
[values[i], values[i + 1]] = [values[i + 1], values[i]];
swapped = true;
}
}
passes++;
if (!swapped) break; // already sorted
}
return { values, passes };
}
const ascending = (a) => bubbleSort(a).values;
const descending = (a) => bubbleSort(a, (x, y) => y - x).values;
const sample = [12, 345, 4, 546, 122, 84, 98, 64, 9, 1, 3223, 455, 23, 234, 213];
console.log('input :', sample.join(', '));
console.log('descending:', descending(sample).join(', '));
console.log("expected : 3223, 546, 455, 345, 234, 213, 122, 98, 84, 64, 23, 12, 9, 4, 1");
console.log('ascending :', ascending(sample).join(', '));
console.log('input afterwards:', sample.length, 'items, unchanged');
console.log('passes for sorted input :', bubbleSort([1, 2, 3, 4, 5]).passes);
console.log('passes for reversed input:', bubbleSort([5, 4, 3, 2, 1]).passes);
Output
16 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 16 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the expected output is descending", descending(sample).join(', '), '3223, 546, 455, 345, 234, 213, 122, 98, 84, 64, 23, 12, 9, 4, 1');
test('ascending is the exact reverse', ascending(sample), descending(sample).slice().reverse());
test('the input is not modified', sample[0], 12);
test('and keeps its length', sample.length, 15);
test('it agrees with a numeric sort', ascending(sample), [...sample].sort((a, b) => a - b));
test('an empty array', ascending([]), []);
test('one element', ascending([1]), [1]);
test('already sorted stays sorted', ascending([1, 2, 3]), [1, 2, 3]);
test('reversed gets fixed', ascending([3, 2, 1]), [1, 2, 3]);
test('duplicates are kept', ascending([2, 1, 2, 1]), [1, 1, 2, 2]);
test('negatives sort correctly', ascending([3, -1, 0, -5]), [-5, -1, 0, 3]);
test('a sorted input needs a single pass', bubbleSort([1, 2, 3, 4, 5]).passes, 1);
test('a reversed input needs n-1', bubbleSort([5, 4, 3, 2, 1]).passes, 4);
test('so the early exit saves real work', bubbleSort([1, 2, 3, 4, 5]).passes < bubbleSort([5, 4, 3, 2, 1]).passes, true);
test('a comparator can sort text', bubbleSort(['c', 'a', 'b'], (a, b) => a.localeCompare(b, 'en')).values, ['a', 'b', 'c']);
test('and objects by a field', bubbleSort([{ n: 2 }, { n: 1 }], (a, b) => a.n - b.n).values.map((o) => o.n), [1, 2]);
Object 6 covers the algorithm. The angle here is the interface: one compare parameter replaces two functions, and the assertions use it to sort numbers ascending, numbers descending, strings and objects with the same body. The sample output is descending — worth noticing, since the prose says nothing about direction and the data says everything.
Two habits carried over: copy the input with [...input] so the caller's array is not reordered, and keep the swapped flag so an already-sorted array costs one pass instead of n−1. Bubble sort is still O(n²) and you should still use sort().
Common mistakes
- Sorting the caller's array in place. Copy it first with
[...input], or the original order is gone. - Guessing the direction from the name. The sample output here is descending. Read the expected data, then pass the matching compare function.
- Using
sort()with no compare function for numbers. It compares them as text, so[10, 9, 1].sort()gives[1, 10, 9]. In real code, usesort((a, b) => a - b)rather than bubble sort, which gets slow on long lists.
Try it yourself
- Sort
[{ n: 2 }, { n: 1 }, { n: 3 }]byn, using a compare function that reads the field. - Add a
swapscounter next topassesand compare it for a sorted and a reversed list. - Sort
['pear', 'apple', 'Fig']withlocaleCompare, then with(a, b) => (a > b ? 1 : -1). The second puts'Fig'first, because capital letters come before small ones in plain string comparison.