Visualize Data Structures & Algorithms in Action
Repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.
Time Complexity: O(n²)
function bubbleSort(arr) {
let 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 arr[j] and arr[j+1]
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
0
0
0ms