Visualizers
Bubble Sort Visualizer
Step-through animation of Bubble Sort with customizable array values.
native (Canvas API)
Client-side
Ready to visualize.
Execution Log
Comparisons: 0
Swaps: 0
Current Action:
Ready
Legend:
Comparing
Swapping
Sorted
Unsorted
Bubble Sort Algorithm
Bubble Sort is a simple comparison-based sorting algorithm. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This pass through the list is repeated until the list is sorted.
Complexity
- Time Complexity: Best $O(n)$, Avg/Worst $O(n^2)$
- Space Complexity: $O(1)$ auxiliary
Implementation
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
const temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}