How soon can a Galway bus app find a route code in an unsorted list?
You’re testing a Galway bus app with made-up route codes. The codes are in no particular order, and you want to know whether a particular code is in the list. How soon can you stop checking?
A Python list keeps its items in the order you put them in. Here, index zero holds forty-two, index one holds seventeen, and index two holds sixty-three. The index tells you where to look. The route code is the value you find there.
Watch the highlight start at the left, where the first code is forty-two. You’re looking for forty-two, so the very first comparison is a match. You can stop at index zero. You don’t need to check any of the other codes.
You’re looking for sixty-three in the same list. You check forty-two first, and it doesn’t match. Before you can reach sixty-three, which code should you compare with the target next? Pick an answer.
This method is called linear search. You compare each item with the target in list order. Stop at the first match, or report that the target wasn’t found when the list ends. You can use linear search on this list as it is. Binary search needs sorted data.
Search the list called codes for eight. At index zero, forty-two doesn’t match. At index one, seventeen doesn’t match. At index two, sixty-three doesn’t match. At index three, twenty-one doesn’t match. At index four, eight matches. Return index four after five comparisons.
Here’s a different list: thirty-one, twelve, fifty-four and twenty-six. You’re searching for ninety-nine. Trace the comparisons in order, then pick the answer that tells you when the search reports that ninety-nine wasn’t found.
Here’s the slip to watch for in Python. If you return minus one inside the loop on a mismatch, the first wrong code ends the search. Keep going after each mismatch. Return minus one after the loop finishes without a match.
In the five-code list, forty-two takes one comparison. Eight takes five, and ninety-nine also takes five because it’s absent. For a list of n items, the worst case takes n comparisons. Double the list length and you double that worst-case count. That’s linear growth, written big O of n.
An exam question could ask you to write a Python function that returns the first matching index, or minus one if the target is absent. Take the list and target, then loop through the indices. Return the index if the value matches. Put the minus one return outside the loop.