Knows the basics
Algorithm Lab
Work through small sorting and search examples by hand, then use code to check your reasoning.
Try an exercise
What you’ll learn
Why does bubble sort bubble?
Compare neighbours and swap out-of-order pairs. Follow where the largest value lands after a full pass.
How can a sort stop early?
Track whether a pass made a swap. Work out what a pass with no swaps tells you about the list.
When can you search half a list?
Use the midpoint to rule out one side of a sorted list. Compare this with checking values one by one.
Try it yourself
Trace one pass of bubble sort
Start with [4, 2, 3, 1]. Work from left to right and swap each adjacent pair whose left number is larger. Write down the list after one pass.
Check your answer
[2, 3, 1, 4]. After the first pass the largest value is at the end. The other values can still be out of order.
Practice plan and checkpoints
Describe what each step changes, then count the total work. Use the same inputs and unit of work when comparing algorithms.
| Sequence | What to do | How to verify it |
|---|---|---|
| First · Bubble once | Write the list after each adjacent comparison. | Explain why the largest element reaches the right end. |
| Second · Stop early | Reset a swap flag each pass and stop after a pass with no swaps. | Try an already sorted list and a reverse-sorted one. |
| Third · Binary search | Use the midpoint to discard one side of a sorted list. | Test a match, a missing value and an empty list. Explain why order matters. |
Work through an example
Find 9 in the sorted list [1, 4, 6, 9, 12]. Use zero-based indices and inclusive endpoints.
Range [0, 4] → index 2 has 6, move the lower bound right
Range [3, 4] → index 3 has 9, foundHow do you establish that 5 is absent?
Discard indices 2 and higher first. Then inspect indices 0 and 1, both below 5. The lower bound crosses the upper bound, so the search is over.
Does it always save work to sort an unsorted list before one lookup?
A linear scan takes one pass at most. Sorting adds work. Compare the total cost when the list is already sorted or the same list will be queried many times.