Loading...
The simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. Named “bubble sort” because smaller elements “bubble” to the top.
*Only optimized version
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
// Time: O(n²), Space: O(1)function optimizedBubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let hasSwapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
hasSwapped = true;
}
}
// If no swaps, array is sorted
if (!hasSwapped) break;
}
return arr;
}
// Best case: O(n), Worst: O(n²)