Bubble SortLoading saved progress…

Bubble Sort

Implement bubbleSort(array), which returns a new array sorted in ascending numeric order using the classic bubble sort algorithm. You repeatedly walk the array comparing each adjacent pair and swapping them when they are out of order; after each full pass the largest remaining value has 'bubbled' up to its final spot at the end. Include the standard optimization: stop early once a pass completes without making any swaps.

Signature

// array:   number[]  — the numbers to sort. NOT mutated.
// returns: number[]   — a NEW array, sorted ascending (numeric order).
function bubbleSort(array): number[];

Examples

bubbleSort([3, 1, 2]);
// → [1, 2, 3]
bubbleSort([5, 4, 3, 2, 1]);
// → [1, 2, 3, 4, 5]

Notes

  • Sort a copy. The input array must be unchanged after the call. Build and return a fresh array.
  • Numeric order, not string order. [10, 2] sorts to [2, 10], not [10, 2]. (The built-in [].sort() would get this wrong without a comparator.)
  • Stop early when sorted. Track a swapped flag per pass; if a pass makes zero swaps the array is already sorted, so break out instead of doing more useless work.
  • Handle the small cases. An empty array returns []; a single element returns itself; duplicates and negative numbers all sort normally.
  • Adjacent swaps only. Bubble sort never compares non-neighbors — every swap is between array[j] and array[j + 1].
Loading editor…