← Algorithms

Bubble sort

Compare adjacent values from left to right and swap them when the left one is larger. Each pass moves the largest remaining value to the end of the unsorted region.

Up to 24 values. Try duplicates or negative numbers.

Step 0 / 23: Original array. Compare adjacent values from left to right.

Array: [5, 2, 4, 2, 1]

Comparisons: 0 · Writes: 0

Green: values in their final positions. Highlighted bars: current comparison or swap. Positions start at zero.

What stays sorted

After each pass, the sorted suffix grows by one: its values are in their final positions. The next pass skips this suffix. If a full pass makes no swaps, the entire array is sorted and the algorithm stops early.

Why the sort is stable

Only strictly greater neighbors are swapped. Equal values never cross, so their original order is preserved. In [5, 2, 4, 2, 1], the first 2 remains before the second 2.

Complexity

Already sorted input
O(n)
Average and worst case
O(n²)
Extra memory of the in-place algorithm
O(1)

The visualizer keeps a complete history of states. Its memory is O(n × number of steps), up to O(n³) for this implementation. This is separate from the memory of the sorting algorithm.

JavaScript implementation

This wrapper copies the input before sorting, so the complete function additionally uses O(n) memory.

function bubbleSort(values) {
    const result = [...values];
    for (let end = result.length - 1; end > 0; end--) {
        let swapped = false;
        for (let i = 0; i < end; i++) {
            if (result[i] > result[i + 1]) {
                [result[i], result[i + 1]] = [result[i + 1], result[i]];
                swapped = true;
            }
        }
        if (!swapped) break;
    }
    return result;
}

Video walkthrough

Built with AlgiViz

This website defines the bubble-sort algorithm. AlgiViz provides immutable array operations, the playback timeline and canvas rendering. Each swap counts as two array writes.