Sorting Algorithm Demo
Comparisons: 1
Time Complexity
Space Complexity
How It Works
Imagine you’re lining up a row of kids by height, shortest to tallest. You start at one end and compare each pair of kids next to each other. If the taller one is on the left, they swap places. You keep doing this, walking down the line over and over, until no more swaps are needed. Each time, the tallest kid left ‘bubbles up’ to the right end, so you check fewer kids each round.
Code
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]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
bubbleSort([5, 3, 8, 4, 2]);