Showing AQAChange board

Deep Dive: Stopping Early

Test yourself on Bubble Sort with exam style questions, marked instantly.

Flashcards that come back just before you would forget them.

A revision plan that remembers what you know and shows what to do next.

See which topics you have nailed and which need another look.

Quiz yourself on Bubble SortGet your flashcardsBuild my revision planTrack my progress

Deep Dive: Stopping Early

A basic bubble sort always makes n - 1 passes. An improved version uses a swap flag.

  1. Set the flag to False at the start of each pass.
  2. Set the flag to True whenever two items are swapped.
  3. At the end of the pass, if the flag is still False, nothing moved, so the list is sorted and the sort stops.

This saves time on lists that are already sorted or nearly sorted. For [1, 2, 3, 5, 4], one pass swaps 5 and 4, and the next pass makes no swaps, so the sort stops after two passes.

A first pass on a list of 5 items makes 4 comparisons, because each pair of neighbours is compared once.

Make this stick

Signing in gives access to all PrepWise features.

PrepWise is a trading name of A3M Quality Solutions Limited, registered in England and Wales, company number 14959172. Registered office: 202 Stroud Road, Gloucester, GL1 5LA. ICO registration ZC267069.