A simple comparison-based algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
O(n²)
O(1)
Yes
Yes
1function bubbleSort(arr) {
2 const n = arr.length;
3 let swapped;
4
5 for (let i = 0; i < n; i++) {
6 swapped = false;
7
8 // Last i elements are already in place
9 for (let j = 0; j < n - i - 1; j++) {
10 // Compare adjacent elements
11 if (arr[j] > arr[j + 1]) {
12 // Swap them if they are in the wrong order
13 [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
14 swapped = true;
15 }
16 }
17
18 // If no swapping occurred in this pass, array is sorted
19 if (!swapped) break;
20 }
21
22 return arr;
23}
24
25// Example usage:
26const array = [64, 34, 25, 12, 22, 11, 90];
27console.log(bubbleSort([...array])); // [11, 12, 22, 25, 34, 64, 90]