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 progressDeep Dive: Stopping Early
A basic bubble sort always makes n - 1 passes. An improved version uses a swap flag.
- Set the flag to False at the start of each pass.
- Set the flag to True whenever two items are swapped.
- 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.