Skip to content
Devtoolry

Arrays and algorithms · intermediate

JavaScript Program for Bubble Sort

Sort an array with bubble sort in JavaScript, step through every swap in the visualizer, stop early when sorted, and use sort() with a compare function.

Bubble sort walks through the array again and again, swapping neighbours that are in the wrong order. After each pass the largest remaining value has bubbled to the end. It is slow for big arrays, but it is the easiest sort to follow step by step.

The program

JavaScript
function bubbleSort(input) {
  const items = [...input];
  for (let end = items.length - 1; end > 0; end--) {
    let swapped = false;
    for (let i = 0; i < end; i++) {
      if (items[i] > items[i + 1]) {
        [items[i], items[i + 1]] = [items[i + 1], items[i]];
        swapped = true;
      }
    }
    if (!swapped) break;
  }
  return items;
}

const data = [5, 1, 4, 2, 8];
console.log(bubbleSort(data).join(" "));
console.log(data.join(" "));
Output
1 2 4 5 8
5 1 4 2 8

How it works

  1. [...input] sorts a copy, so the caller's array is unchanged (the last line proves it).
  2. end marks where the unsorted part stops; it moves one place left after each pass.
  3. Neighbours in the wrong order are swapped with destructuring.
  4. If a whole pass makes no swap, the array is sorted and break stops early.

Watch it run line by line

This is the program to visualize: watch items change after each swap, i walk along the array, and end shrink after each pass. Try [1, 2, 3, 4, 5] to see the early exit after one pass.

“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.

Another way: What to use in real code

Array.prototype.sort() sorts in place, but compares elements as strings unless you pass a compare function. toSorted() (ES2023) returns a sorted copy.

JavaScript
const data = [5, 1, 40, 2, 8];
console.log([...data].sort().join(" "));
console.log([...data].sort((a, b) => a - b).join(" "));
console.log(data.toSorted((a, b) => b - a).join(" "));
Output
1 2 40 5 8
1 2 5 8 40
40 8 5 2 1

Common mistakes

  • Calling sort() on numbers without a compare function: 40 sorts before 5 because "4" < "5".
  • Looping i < items.length in the inner loop, so items[i + 1] is undefined on the last pass.
  • Swapping with two assignments (items[i] = items[i + 1]; items[i + 1] = items[i]), which copies one value over the other.

Try it yourself

  • Count swaps and comparisons for a sorted, a reversed and a random array.
  • Sort an array of objects by an age property.

Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.

Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.