Loading...
Bubble sort repeatedly compares adjacent items. Identify the pass direction and stopping rule before tracing exactly which swaps occur.
What you'll be able to do
For ascending order with a left-to-right pass, compare adjacent values and swap when the left is larger. After one complete pass, the largest remaining value has moved to the far right of the active region. Repeat while excluding the suffix already known to be in position.
An implementation might scan in the opposite direction, producing different intermediate states while reaching the same final order. An exam trace must follow the stated version. A “pass” normally means a complete traversal of the current comparison range, not one swap.
With n items, a simple version needs up to n-1 passes. On each pass the active end can shrink because one more largest value is fixed. A swapped flag can end the algorithm after a complete pass with no swaps, showing that all adjacent pairs in the active region are ordered.
The flag must be reset for each pass. Stopping after one comparison with no swap is incorrect because a later pair may still be reversed. Equal values should not be swapped unnecessarily when preserving the input order of equal-key records is desired.
The worst-case comparison count for the shrinking-bound version is (n-1)+(n-2)+…+1, which is n(n-1)/2 and O(n²). An early-exit implementation can recognise already sorted data in O(n) time; a version without that test still performs its scheduled passes.
The ordinary in-place algorithm uses constant extra storage, but its many comparisons and swaps make it inefficient for large inputs. Do not use one small timing result as a universal complexity proof. Count how the required operations grow with n under a stated case.
| Stage | Sequence |
|---|---|
| Start | 5, 1, 4, 2 |
| After pass 1 | 1, 4, 2, 5 |
| After pass 2 | 1, 2, 4, 5 |
| Pass 3, no swaps | 1, 2, 4, 5 |
Attempt the task before opening its worked response. Record each change of state, explain the rule used, and check the result against the original requirements. Code examples labelled Python 3 use that language’s conventions; pseudocode states its own assumptions.
Common mistakes to avoid
Key takeaways
Test yourself
Answer a few questions, then review anything you missed.
Start with the quiz above to check the key ideas. You can also choose another topic from the practice library.