The simplest sorting algorithm that repeatedly steps through the list
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.
The pass through the list is repeated until the list is sorted. The algorithm gets its name because smaller elements "bubble" to the top of the list.
function bubbleSort(arr) {
let n = arr.length;
let swapped;
do {
swapped = false;
for (let i = 0; i < n - 1; i++) {
// Compare adjacent elements
if (arr[i] > arr[i + 1]) {
// Swap if they are in wrong order
[arr[i], arr[i + 1]] = [arr[i + 1], arr[i]];
swapped = true;
}
}
// After each pass, largest element bubbles to end
n--;
} while (swapped);
return arr;
}
You can optimize by reducing the inner loop size after each pass since the largest elements bubble to the end.
Only suitable for small datasets or nearly sorted data. For larger datasets, consider more efficient algorithms like quicksort or mergesort.