FlowLab Logo

Bubble Sort Visualizer

SlowFast
520
(7)
Comparing
Swapping
Sorted
Operation Logs
No operations yet
Algorithm Info
Time Complexity: O(n²) worst and average case, O(n) best case
Space Complexity: O(1) - in-place sorting
Stable: Yes - maintains relative order of equal elements
How it works: Repeatedly compares adjacent elements and swaps them if they're in wrong order. Each pass moves the largest unsorted element to its correct position.
Optimization: Can stop early if no swaps occur in a pass (array is sorted).
Implementation
function bubbleSort(arr) {
  const n = arr.length;
  
  for (let i = 0; i < n - 1; i++) {
    let swapped = false;
    
    for (let j = 0; j < n - i - 1; j++) {
      // Compare adjacent elements
      if (arr[j] > arr[j + 1]) {
        // Swap if out of order
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        swapped = true;
      }
    }
    
    // If no swapping occurred, array is sorted
    if (!swapped) break;
  }
  
  return arr;
}