Theory
Bubble Sort repeatedly compares adjacent elements and swaps them when they are in the wrong order. After each pass, the largest unsorted element moves toward the end. Its average and worst-case time complexity is O(n²).
Example
const numbers = [5, 3, 4, 1];
for (let i = 0; i < numbers.length; i++) {
for (let j = 0; j < numbers.length - i - 1; j++) {
if (numbers[j] > numbers[j + 1]) {
const temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
console.log(numbers);
Expected Output
[1, 3, 4, 5]
Practice
Implement Bubble Sort and count how many swaps are performed.
Interview Questions
- How does Bubble Sort work?
- What is its worst-case complexity?
- Is Bubble Sort stable?
- When is Bubble Sort useful?