At a Leeds school fair, is binary search always quicker at finding your raffle ticket?
At a school fair in Leeds, you have thirty-one raffle tickets to check. A friend says binary search will always find a ticket faster. What if the ticket you want is the very first one in the list?
Linear search starts at the first entry and checks one at a time, in any order. Binary search checks the middle. If it doesn't match, repeat on the left for a smaller target or on the right for a larger one. This needs sorted data. Count one comparison per entry checked.
Start with the tickets in number order, from one to thirty-one. To find ticket one, linear search stops after just one comparison. Binary search starts in the middle and keeps looking in the lower half. It takes five comparisons to reach ticket one.
Now you're looking for ticket sixteen in the same sorted list. Think about where each search starts and how far it has to go. Pick the pair of comparison counts.
Trace binary search for ticket one: sixteen, eight, four, two, one. That's five checks. Now try ticket thirty-two, which is missing. Linear search checks all thirty-one tickets. Binary search checks sixteen, twenty-four, twenty-eight, thirty and thirty-one. The range is now empty, so it stops after five checks.
This time the sorted list runs from one to fifteen, and you're looking for sixteen. Start binary search at ticket eight and follow the upper half each time. Pick how many comparisons each search makes.
The same thirty-one tickets are shown in order and shuffled, with ticket one still first. The bottom row counts checks for tickets one and thirty-two. In order, linear takes one or thirty-one, and binary takes five for either. After shuffling, linear's counts stay the same. Binary search needs sorted data.
Suppose you try binary search for ticket thirty-one after the shuffle. The middle ticket is eight, so binary search would discard the left half. But ticket thirty-one is sitting in that half. In the sorted list, going right from the middle really does keep ticket thirty-one in play.
If the exam asks you to evaluate which search to use, consider the order and how often you'll search. For one shuffled search, linear starts straight away but may check every entry. For repeated searches, consider binary. If sorting is needed, will the later searches save enough work to justify it?