Back to Visualizer
Bubble Sort
Bubble Sort is a simple comparison-based sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
Best: O(n)Avg: O(n²)Space: O(1)
Size:20
Speed:50%
Default
Comparing
Swapping
Sorted
Pivot
Current
0
Comparisons
0
Swaps
How It Works
- 1Start from the first element and compare adjacent elements
- 2If the current element is greater than the next, swap them
- 3Continue to the end of the array (this completes one pass)
- 4The largest element 'bubbles up' to its correct position
- 5Repeat for remaining unsorted portion
- 6Stop when no swaps are needed in a complete pass
Time Complexity
Best CaseO(n)
Average CaseO(n²)
Worst CaseO(n²)
Space ComplexityO(1)
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]) {
// Swap elements
[arr[j], arr[j+1]] = [arr[j+1], arr[j]];
}
}
}
return arr;
}