Algorithm Visualizer

Interactive learning platform for algorithms and data structures
500ms
Time Complexity:
Best: O(n)Avg: O(n²)Worst: O(n²)
Space:O(1)
Stable:Yes

Bubble Sort

Starting Bubble Sort algorithm

Loading...
Comparing
Swapping
Current
Sorted
Step 1 of 2

Implementation

Bubble Sort

function bubbleSort(arr) {
  const n = arr.length;
  
  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - i - 1; j++) {
      // Compare adjacent elements
      if (arr[j] > arr[j + 1]) {
        // Swap elements
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  
  return arr;
}

Description

Repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.