AV

Learn Algorithms

Master algorithms through interactive step-by-step visualization

Bubble Sort

Sorting

Easy

Bubble Sort is an elementary sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in wrong order. It is named because smaller elements "bubble" to the top of the list.

Time Complexity

O(n²)

Space Complexity

O(1)
Bubble Sort.js
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
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
}

Key Points

  • Compares adjacent elements
  • Swaps if in wrong order
  • Largest element "bubbles" to end
  • Stable sorting algorithm
  • In-place sorting
  • Not suitable for large datasets

Resources

Your Progress

60% complete