Menu

Sorting Algorithms

Bubble Sort Best and Worst Cases

Bubble sort has a best case and a worst case, depending on the order of the list before sorting starts. The case tells you how many passes, swaps and comparisons the algorithm needs.

Best case: already in order

If the list is already sorted, the first pass compares neighbouring items and finds every pair in the right order, so it makes no swaps. A bubble sort that checks whether any swaps happened can then stop after that one pass. This is the best case because it needs the fewest comparisons.

For example, quiz scores 14, 17, 21, 26 are already in ascending order. One pass compares 14 with 17, then 17 with 21, then 21 with 26. Nothing is out of order, so no swaps occur and the sort ends.

Worst case: reverse order

If the list is in reverse order, almost every comparison finds a pair the wrong way round, so every pass makes swaps. Because a swap happens on every pass, the check for swaps can never stop the sort early, so it needs the most passes, the most swaps and the most comparisons. This makes it the slowest case.

For example, 26, 21, 17, 14 needs several passes. The first pass swaps 26 with 21, then 26 with 17, then 26 with 14, so 26 reaches the end straight away, but only one item is placed in its final position each pass. More passes are still needed before the list is sorted.

Bubble sort passes for 26, 21, 17, 14 (worst case) showing the list after each pass and the swaps, and for 14, 17, 21, 26 (best case) where one pass makes no swaps and the sort stops.

CaseStarting listPassesSwapsComparisons
BestAlready in orderOneNoneFewest
WorstReverse orderMostMostMost

Practise this