Bubble Sort
Receives an array of integers and sorts it in ascending order using bubble sort. It makes repeated passes over the unsorted portion: on each pass it compares every adjacent pair — if the left value is greater than the right, they are swapped — so the largest unsorted value bubbles to its final position at the end. Each subsequent pass covers one fewer element because the last position of the previous pass is already settled; an early-exit check stops the algorithm as soon as a full pass makes no swaps, because the array is already in order. Returns a new array with the values in ascending order.
Visualization
- Input
- Result
Algorithm code
// Bubble sort — a single pure function. Receives an array of integers and
// returns a new array sorted in ascending order, making repeated adjacent-swap
// passes with an early-exit check: if a pass makes no swaps, the array is done.
/**
* @param {number[]} arr - array of integers to sort
* @returns {number[]} a new array with the values in ascending order
*/
export function bubbleSort(arr) {
const result = [...arr];
const n = result.length;
for (let i = 0; i < n - 1; i += 1) {
let swapped = false;
for (let j = 0; j < n - 1 - i; j += 1) {
if (result[j] > result[j + 1]) {
const temp = result[j];
result[j] = result[j + 1];
result[j + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
}
return result;
} FUNCTION bubbleSort(arr):
result ← copy(arr)
n ← length(result)
FOR i ← 0 TO n - 2:
swapped ← false
FOR j ← 0 TO n - 2 - i:
IF result[j] > result[j + 1]:
swap(result, j, j + 1)
swapped ← true
IF NOT swapped:
BREAK
RETURN result