Unsorted
Comparing
Swapping
Sorted
Sorting Statistics
Comparisons
0
Swaps
0
Passes
0
Time
0 ms
How Bubble Sort Works
1
Compare Adjacent Elements
Start from the first element and compare it with the next element.
2
Swap if Needed
If the first element is greater than the second, swap them.
3
Move to Next Pair
Move to the next pair of adjacent elements and repeat.
4
Complete Pass
After each pass, the largest element "bubbles up" to its correct position.
5
Repeat
Repeat the process for the remaining unsorted portion until the array is fully sorted.
Bubble Sort Algorithm
function bubbleSort(arr) {
let n = arr.length;
let swapped;
for (let i = 0; i < n - 1; i++) {
swapped = false;
for (let j = 0; j < n - i - 1; j++) {
// Compare arr[j] and arr[j+1]
if (arr[j] > arr[j+1]) {
// Swap elements
[arr[j], arr[j+1]] = [arr[j+1], arr[j]];
swapped = true;
}
}
// If no swaps occurred, array is sorted
if (!swapped) break;
}
return arr;
}