Skip links
Reza Ghaderipour points to Mina, the middle of seven alphabetically ordered name cards.

Linear vs. Binary Search: 1 Contact List, 2 Ways to Find Name

Share

When I first tried LeetCode, seeing “Accepted” was a relief. Then I looked at the runtime. My code had found the answer, and I still couldn’t explain why it had taken so much work. That experience is why I put the fundamentals first in my roadmap for learning algorithms. Here’s the exercise I’d start with after reading it.

Suppose I hand you seven contact cards and ask you to find Nia. If I hand them to you in the order they came in, you can read from the front until you reach her. That’s linear search. If I’ve already alphabetized the cards, you can check the middle one and use its name to rule out half the pile. That’s binary search.

Now suppose I want only one phone number and the cards are still in a jumble. Would you alphabetize them for me first? Keep that question in mind as we try both approaches in Python.

Linear search on the list you actually have

Here are the contacts in the order they arrived. Our function should return a matching index, counting from zero, or None if the name is missing. Both versions will follow that contract.

names = ["Mina", "Ava", "Sami", "Leo", "Ben", "Nia", "Zoe"]

Read the names out loud and stop as soon as you find Nia. You’ll say Mina, Ava, Sami, Leo, Ben, Nia. You can hand back her card without ever reading Zoe’s. Six names examined, index 5 returned.

Linear search checks Mina, Ava, Sami, Leo, Ben and then Nia, leaving Zoe unread
Nia is the sixth name checked and sits at index 5

Turn the finger scan into Python

def linear_search(names, target):
    for index, name in enumerate(names):
        if name == target:
            return index
    return None

print(linear_search(names, "Nia"))   # 5

enumerate gives us the position and the name together. The indentation of return None matters: it sits outside the loop. Move it inside, and a mismatch on Mina would end the whole search before you even reached Ava.

If the first name matches, this takes one check. If the name is missing, it takes all seven. For a list of n names the worst-case number of entries examined is n, which gives us O(n) search time for fixed-cost comparisons.

Binary search on the same seven names

Alphabetize one copy: Ava, Ben, Leo, Mina, Nia, Sami, Zoe. The middle name is Mina. Nia comes later, so everything through Mina can go. The remaining names are Nia, Sami and Zoe. Their middle is Sami. This time go left. That leaves Nia, at index 4 in the sorted copy.

On the sorted list, binary search checks Mina at index 3, Sami at 5 and Nia at 4
Only the names inside the active range can still match.

Keep track of what could still be true

def binary_search(names, target):
    low, high = 0, len(names) - 1
    while low <= high:
        mid = (low + high) // 2
        name = names[mid]
        if name == target:
            return mid
        if name < target:
            low = mid + 1
        else:
            high = mid - 1
    return None

ordered = sorted(names)
print(binary_search(ordered, "Nia"))   # 4

low and high include both ends. If they meet, one candidate remains, so the loop uses <=. The +1 and −1 move past a name we already checked. Once low passes high, there’s nowhere left to look. Notice that the returned index changed when we sorted the list.

Is sorting worth it for one lookup?

For this particular lookup we inspected six names in arrival order and three in sorted order. Those three checks leave out a piece of work: somebody had to put the cards in order. If I’m finding Nia once in a fresh export, I’ll scan it and get on with my day.

What changes when the list gets bigger?

On a sorted Python list of 1,000 names, the middle-check loop above inspects at most 10 entries. A linear search for an absent name inspects all 1,000. Doubling a sorted list to 2,000 adds just one middle check in the worst case. That slow growth is what O(log n) describes. We’re counting entries inspected, so these numbers aren’t predictions in milliseconds. See how Khan Academy measures algorithm efficiency.

What changes when the searches keep coming?

Picture a receptionist looking up names in the same directory all afternoon. If the list is already alphabetized, each lookup can use binary search immediately. If it arrives unsorted but stays stable, sorting once lets every later lookup reuse that work. For q lookups, repeated scans cost O(qn) in the worst case; with a comparison sort, sorting once and searching costs O(n log n + q log n).

There’s no universal number of lookups at which sorting pays off. An early match, the cost of comparing the names and how often the directory changes all affect that decision. Both search loops use O(1) extra space. The sorted copy we created in Python uses O(n) additional space. Harvard’s CS50 handout walks through the sorting trade-off.

Two quick checks before you move on

  1. Try to find Ben with binary search on the original, unsorted list. Which comparison loses him? Answer: the middle name is Leo. Ben comes before Leo alphabetically, so the code discards the right side, including the actual Ben at index 4. The code finishes and quietly returns None.
  2. Someone asks for Noor in the sorted list. Which names will you inspect? Answer: Mina, Sami, then Nia. Noor would come after Nia and before Sami. At that point low is 5 and high is 4. An empty range is a perfectly good answer.

Frequently asked questions

Does linear search work on a sorted list?

Yes. It can scan any list from the beginning. On our sorted list, looking for Ava takes one check with linear search and three with binary search. The worst-case comparison tells you how a method scales. The particular name you ask for still matters.

What if the same name appears twice?

The linear function returns the first match. The binary function above returns whichever matching entry it reaches first, which can be a later occurrence. If you need the leftmost match in a sorted Python list, bisect_left gives you a candidate position. Check the bounds and the value there before returning it. Python’s bisect documentation explains how insertion points work.

Why does my code miss the last item or loop forever?

Trace a one-name list, first with a matching target, then with a missing one. In this version, low == high means you still have one name to inspect. After a mismatch, setting low = mid or high = mid can leave the same name in play forever. Move past mid and you can see the range shrink on paper.

What would I use for a real contact app?

For occasional lookups in a short list, a scan is fine. For repeated exact lookups by a unique contact ID, I’d also consider a Python dictionary. An ordered list earns its keep when you need alphabetical browsing or the position where a new name belongs. What you need to do after finding a match is part of the choice.

About the author

I’m Reza Ghaderipour, a self-taught developer. I write about the parts of building software that clicked for me only after I tried them on a small problem. If you’re working through the fundamentals, read more of my posts. And if you try the seven-card exercise with someone, connect with me on LinkedIn and tell me which comparison made it click.

Leave a comment

This website uses cookies to improve your web experience.