64
34
25
12
22
11
90
0
1
2
3
4
5
6
Starting Bubble Sort. We will repeatedly compare adjacent elements.
Presets:
Size:
Timeline Progress:
0%Step 1 / 43
Comparisons
0
Swaps / Actions
0
Speed:
Shortcuts: Space Play ⢠ā/ā Step ⢠R Reset ⢠M Sound ⢠Z Focus
Implementation Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function bubbleSort(arr: number[]): number[] {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
let swapped = false;
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]];
swapped = true;
}
}
if (!swapped) break;
}
return arr;
}Complexity Analysis
Best Case
O(n)
Average Case
O(n²)
Worst Case
O(n²)
Space
O(1)
StableIn-Place
Color Legend
Unsorted
Comparing
Swapping
Sorted
Bubble Sort is the simplest sorting algorithm. It repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. After each full pass, the largest unsorted element "bubbles up" to its correct position.