Bubble Sort Visualization
Bubble Sort
Algorithm Explanation
Bubble Sort is a simple sorting algorithm that 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.
Time Complexity:
- Best Case: O(n) - when the array is already sorted
- Average Case: O(n²)
- Worst Case: O(n²) - when the array is sorted in reverse order
Space Complexity: O(1)
Custom Input
Enter numbers separated by commas. Example: 5, 3, 8, 1, 2
Code Implementation
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n - i - 1; j++) {
// Compare adjacent elements
if (arr[j] > arr[j + 1]) {
// Swap them if they are in the wrong order
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}