# Bubble Sort visualised: comparisons, swaps, O(n^2)

> Interactive Bubble Sort: bars show every comparison and swap, pseudocode highlights the active line. With runtime in every case, stability and use cases.

Address: https://marckimmel.de/en/informatik/sortieralgorithmen/bubble-sort
Deutsche Fassung: https://marckimmel.de/informatik/sortieralgorithmen/bubble-sort.md

Compares adjacent elements in every pass and bubbles the largest to the end.

Bubble Sort sweeps through the array from left to right, comparing two adjacent elements at every step. When they are in the wrong order it swaps them. After one full pass the largest element has bubbled to the right end, so the next pass can ignore it and the considered range shrinks by one. After at most n passes the array is sorted. A small optimisation tracks whether any swap happened during a pass: if not, the array is already sorted and the algorithm exits immediately. This early-exit produces the linear best-case runtime O(n) on already-sorted input. Average and worst case need quadratically many comparisons and swaps (O(n^2)). Memory stays constant since all swaps happen inside the input array (O(1)). Bubble Sort is stable: equal elements keep their relative order.

In practice almost only useful for teaching. Bubble Sort needs quadratically many steps and is therefore much slower than Insertion or Merge Sort. It only pays off when the code has to be minimal, the array has very few elements, or the data is already almost sorted. The early-exit variant detects a sorted input after one pass and stops immediately.

## Related

- [Sorting Algorithms](https://marckimmel.de/en/informatik/sortieralgorithmen.md)
