lou.tools
EN

Bubble sort

Bubble sort, step by step

Watch it sort any list, step by step, with its pseudocode and its Python.

Updated

Free, in your browser. Your lists never leave it.Privacy

8 values to sort.

Comparisons: 0Swaps: 0

What happens next?

The run stops five times and asks what comes next. Answer, and it plays on.

Pseudocode and implementation

Pseudocode

  1. Take the list; n is how many values it has.
  2. Repeat one pass for each value still out of place, and note that the pass has swapped nothing yet:
  3. Walk the unsorted part, one pair of neighbours at a time:
  4. If the left value is greater than the right one,
  5. swap them and note that the pass swapped something.
  6. If the whole pass swapped nothing, the list is sorted: stop.
  7. Return the sorted list.

Python

def bubble_sort(a):    n = len(a)    for i in range(n - 1):        swapped = False        for j in range(n - 1 - i):            if a[j] > a[j + 1]:                a[j], a[j + 1] = a[j + 1], a[j]                swapped = True        if not swapped:            break    return a

How it works

Bubble sort compares each value with the one to its right and swaps them when the left one is greater. One walk along the list is a pass. Each pass carries the greatest value still out of place to the end, like a bubble rising, so the unsorted part gets one value shorter every time.

If a whole pass swaps nothing, every neighbour is already in order and the list is sorted, so the algorithm stops early. That is why a list that is already sorted takes a single pass: n − 1 comparisons and no swaps.

In the worst case, a list in reverse order, every pair is swapped: about n²/2 comparisons and as many swaps. It needs no extra memory and never swaps equal values, so it is stable.

Complexity

Best caseO(n)
Average caseO(n²)
Worst caseO(n²)
Extra spaceO(1)
StableYes
In placeYes

n is how many values the list has.

Questions

When is bubble sort a good choice?
To learn how sorting works, and for very short or nearly sorted lists. For real lists of any size, merge sort, quicksort or your language’s own sort are much faster.
How is it different from insertion sort?
Both are O(n²) in the worst case and stable. Bubble sort moves the greatest value to the end on each pass; insertion sort takes each value and slides it left into the part already in order. Insertion sort usually makes fewer comparisons.
What is the most common mistake?
Walking the whole list on every pass. After pass k the last k values are already in place, so the inner loop can stop k positions earlier, as range(n - 1 - i) does in the Python.
How does "What happens next?" work?
It runs bubble sort on a new random list and stops five times to ask what comes next: whether two values are swapped, which pair is compared, or how the list looks after a pass. Your answers stay in your browser.

More algorithms