← Back

Bubble Sort

comparisonin-placestable
Press play to start
1function bubbleSort(arr: number[]): number[] {
2 for (let i = 0; i < arr.length - 1; i++) {
3 for (let j = 0; j < arr.length - 1 - i; j++) {
4 if (arr[j] > arr[j + 1]) {
5 [arr[j], arr[j+1]] = [arr[j+1], arr[j]]
6 }
7 }
8 }
9 return arr
10}
Step 1/0
Custom array:

Complexity

Best:O(n)
Average:O(n²)
Worst:O(n²)
Space:O(1)

Description

Repeatedly compares adjacent elements and swaps them if they are in the wrong order, causing larger elements to 'bubble up' to the end.

When to use

Primarily educational. Acceptable for very small arrays or nearly-sorted data where simplicity matters more than performance.