Bubble Sort
Sortingeasy#1Repeatedly swap adjacent elements if they are in wrong order
Ready
Step 1 of 0
Speed
Input Data
Comma-separated numbers (0-999). Min 2 values.
Algorithm Code
1function bubbleSort(arr) {2 const n = arr.length;3 for (let i = 0; i < n - 1; i++) {4 for (let j = 0; j < n - i - 1; j++) {5 if (arr[j] > arr[j + 1]) {6 [arr[j], arr[j+1]] = [arr[j+1], arr[j]];7 }8 }9 }10 return arr;11}
Best
O(n)
Average
O(n²)
Worst
O(n²)
Space
O(1)
About Bubble Sort
Bubble Sort 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. It gets its name because smaller elements 'bubble' to the top of the list.
Time Complexity: Best: O(n), Average: O(n²), Worst: O(n²). Space: O(1).