Bubble Sort

Repeatedly swaps adjacent elements that are out of order until the array is sorted.

Syntax

bubbleSort(arr)

Parameters

NameTypeRequiredDescription
arr Array<number> Yes The mutable array of numbers to sort in-place.

Returns

void — Sorts the input array in-place; returns nothing.

Examples

function bubbleSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    let swapped = false;
    for (let j = 0; j < n - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        swapped = true;
      }
    }
    if (!swapped) break; // already sorted
  }
}

const nums = [5, 3, 8, 1, 2];
bubbleSort(nums);
console.log(nums);
Output
[ 1, 2, 3, 5, 8 ]
// Edge case: already sorted — exits after one pass
function bubbleSort(arr) {
  const n = arr.length;
  for (let i = 0; i < n - 1; i++) {
    let swapped = false;
    for (let j = 0; j < n - 1 - i; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        swapped = true;
      }
    }
    if (!swapped) break;
  }
}

const sorted = [1, 2, 3, 4, 5];
bubbleSort(sorted);
console.log(sorted);
Output
[ 1, 2, 3, 4, 5 ]

Notes

| Case | Time | Space | |---------|--------|-------| | Best | O(n) | O(1) | | Average | O(n²) | O(1) | | Worst | O(n²) | O(1) | Best case O(n) is achieved with the early-exit `swapped` flag when the array is already sorted. Bubble sort is stable (equal elements keep their relative order). In practice, prefer insertion sort for nearly sorted data; bubble sort is mainly a teaching tool.

See also