Bubble Sort

Bubble Sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. It continues this process until the entire array is sorted.

Although it's easy to understand, Bubble Sort is not efficient for large datasets due to its O(n²) time complexity.

Example

// Bubble Sort in JavaScript
function bubbleSort(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
      }
    }
  }
  return arr;
}

console.log(bubbleSort([5, 2, 9, 1, 5, 6])); // Output: [1, 2, 5, 5, 6, 9]
Bubble Sort

Build Array

6 elements

Start with an empty array of a chosen length. New slots start as NULL — fill them with Push or Insert below.

Sort

Compares each adjacent pair, one step at a time, and swaps them if they're out of order.

Pass: 0Comparison: 0
Speed
Array Visualizer
6 elements
0
1
2
3
4
5
220
148
101
64
53
8
Comparing
Swapping
Sorted
Real-life Use (Bubble Sort)

Bubble Sort can be used in situations where the dataset is small and performance is not a critical factor.

For example, it's useful for teaching sorting concepts or when sorting a small number of items like organizing names alphabetically in a classroom list.

Example

// Sorting student names alphabetically using Bubble Sort
const names = ["Rita", "Amit", "Kunal", "Sneha"];
bubbleSort(names);
console.log(names); // Output: ["Amit", "Kunal", "Rita", "Sneha"]