Bubble Sort
Aligned to the AQA 8525 specification
- Level
- Intermediate
- Reading time
- 6 min
- Published
- 6 June 2026
- Updated
- 1 July 2026
On this page
Key takeaways
- Bubble sort compares adjacent pairs and swaps them if they are in the wrong order, repeating across passes until no more swaps are needed.
- After k passes the k largest elements are in their correct positions at the end of the list; after just one pass only the largest element is guaranteed to be in place.
- For a list of n elements, at most n - 1 passes are needed, and each pass can shorten its comparison range by one since the last elements are already sorted.
- The swap flag optimisation sets a flag to False at the start of each pass and to True on any swap, exiting early if no swap occurs, giving a best case of O(n).
- Bubble sort's worst-case time complexity is O(n^2) because total comparisons equal n(n-1)/2, so doubling the list size quadruples the comparisons.
Something not quite clicking?
Ask Aica to explain any part of this differently. Free, takes 30 seconds.
Frequently asked questions
In the worst case each pass makes one fewer comparison than the last, so the total is (n-1) + (n-2) + ... + 1 = n(n-1)/2. Since this is approximately n^2/2, the complexity is written O(n^2), meaning doubling the list size roughly quadruples the number of comparisons.
It lets bubble sort exit early once the list is sorted. A flag is set to False at the start of each pass and to True if any swap occurs. If the flag is still False at the end of a pass, no swaps happened, the list is sorted and the algorithm stops, giving a best case of O(n).
Bubble sort is preferred when the list is very small, when it is nearly sorted so the swap flag exits after few passes, or when memory is severely constrained, since it sorts in place using no extra memory while merge sort needs additional space proportional to n. For large unsorted datasets merge sort is generally better.
Generate revision on any topic you study
Type any topic you're studying and Aicademy generates a complete lesson, quiz, and flashcard set, personalised to your level.
Lessons on anything
Structured, level-matched lessons on any topic you study
Practice quizzes
Find out what you actually know before the exam does
Flashcard sets
Lock in key concepts with instant revision cards
Ask Aica
Stuck on something? Get a clear explanation, any time
Linear Search and Binary Search
Merge Sort