Sub topic 1
What It Means to Search a Collection
Searching is one of the most common things a program does. A login checks whether a username exists, a compiler looks up a variable name, and a store page finds the price for a product ID. Before comparing search algorithms, you need a precise statement of the problem they solve. This chapter defines the search problem, the questions you can ask of a collection, the contracts a search function can offer, and the cost model used for the rest of the tutorial.
Prerequisites
This chapter assumes you are comfortable with:
- Basic programming in a language such as Python or Java
- Arrays or lists and zero-based indexing
- Loops, conditionals, and functions
- Basic familiarity with Big-O notation (for example, knowing that O(n) grows linearly with input size)
The examples use Python 3. Later chapters also show Java where fixed-width integers matter.
The Search Problem, Stated Precisely
A search takes two inputs:
- A collection: a sequence of elements
a[0], a[1], ..., a[n-1], wherenis the length. - A target: the value (or key) you are looking for.
It produces one output: some answer about where, or whether, the target appears in the collection.
That definition leaves three things open. A real search function has to settle each of them.
| Decision | Options | Example |
|---|---|---|
| What counts as a match | Equality of whole values, equality of a key field, a predicate | `x == 7`, `user.id == 42`, `x > 100` |
| What question is answered | Membership, first index, last index, all indices, count, insertion point | "Is 7 present?" vs. "Where would 7 go?" |
| How "not found" is reported | Sentinel value, `None`, exception, encoded insertion point | `-1`, `None`, `ValueError`, `-(ip) - 1` |
Each of these choices shapes how callers use the function and which bugs they are likely to write.
What Counts as a Match
The simplest case compares whole values with ==. Real data is usually made of records, though, and you search by one field of each record, called the key.
users = [
{"id": 17, "name": "Ana"},
{"id": 42, "name": "Bo"},
{"id": 58, "name": "Cy"},
]
match = next((u for u in users if u["id"] == 42), None)
print(match) # {'id': 42, 'name': 'Bo'}
missing = next((u for u in users if u["id"] == 99), None)
print(missing) # NoneThe idea generalizes: a match is any element for which a predicate (a function returning true or false) holds. "Find the first order over $100" is a search with the predicate order.total > 100. A later chapter uses this view to binary-search over a range of candidate answers.
Equality pitfalls
Your definition of a match is only as reliable as the comparison behind it.
- Floating-point values.
0.1 + 0.2 == 0.3isFalsein Python and most other languages. Searching for a computed float with==can miss a value that looks identical when printed. Compare with a tolerance instead. - Identity vs. equality. In Python,
ischecks whether two names refer to the same object, while==checks whether the values are equal. In Java,==on objects compares references, so strings and boxed numbers need.equals(). - Case and normalization.
"Bob"and"bob"are different strings. Decide whether matching ignores case, and normalize both sides the same way.
import math
readings = [0.1, 0.30000000000000004, 0.5]
target = 0.3
print(target in readings) # False: exact equality fails
print(any(math.isclose(x, target) for x in readings)) # TrueWhat Question Is Being Asked
"Search" covers several questions. They cost different amounts of work, so name the one you need before you pick an algorithm.
| Question | Typical return | Can stop at first match? |
|---|---|---|
| Is the target present? | `bool` | Yes |
| Where is the first occurrence? | index | Yes, if scanning from the left |
| Where is the last occurrence? | index | Yes, if scanning from the right |
| Where are all occurrences? | list of indices | No, must examine everything |
| How many occurrences? | `int` | No, unless the data is sorted |
| Where would the target be inserted to keep order? | index from 0 to `n` | Only meaningful on sorted data |
Python's built-ins answer several of these directly:
a = [4, 2, 7, 2, 9]
print(7 in a) # True (membership)
print(a.index(2)) # 1 (first occurrence)
print(a.count(2)) # 2 (count)
print([i for i, x in enumerate(a) if x == 2]) # [1, 3] (all occurrences)The insertion-point question needs a sorted collection, and so does the fast way to count duplicates. The lower-bound and upper-bound chapters cover both.
How "Not Found" Is Reported
Every search must handle a target that isn't there. The way the function reports that case is part of its contract. A mismatch between what the function returns and what the caller expects is one of the most common search bugs.
| Convention | Example | Strength | Risk |
|---|---|---|---|
| Sentinel `-1` | C-style functions, Java `indexOf` | Cheap, always an `int` | In Python, `a[-1]` is a valid index (the last element) |
| `None` / `null` | Many Python helpers | Clearly distinct from any index | Caller forgets to check, then crashes later |
| Exception | Python `list.index` raises `ValueError` | Impossible to ignore silently | Exceptions used for normal control flow |
| Encoded insertion point | Java `Arrays.binarySearch` returns `-(ip) - 1` | Carries extra information | Easy to misread as a plain "not found" |
The -1 convention is especially dangerous in Python because negative indices count from the end:
items = [4, 2, 7, 1]
idx = -1 # pretend a search returned "not found"
print(items[idx]) # 1 -- no error, just the wrong elementThe code runs, prints a plausible value, and hides the bug. If you return -1, every caller must check idx == -1 (or idx < 0) before indexing. In Python, a function that returns None or raises an exception is often safer:
a = [4, 2, 7, 1]
try:
pos = a.index(5)
except ValueError:
pos = None
print(pos) # NoneWhat You Know About the Data
The best algorithm depends less on the target than on what you already know about the collection.
- No ordering. If the elements are in arbitrary order, no single comparison tells you anything about the others. You may have to look at every element. This is linear search.
- Sorted order. If
a[0] <= a[1] <= ... <= a[n-1], one comparison with a middle element tells you which half could hold the target. You can discard the other half without looking at it. This is binary search. - Indexed by key. If the data lives in a hash table (a Python
dictorset, a JavaHashMap), lookup by exact key takes expected constant time. This tutorial focuses on sequences, but keep this option in mind. Sometimes the right fix for slow searching is a different data structure.
Sortedness is a property of the data plus the comparison you use. A list sorted by name is not sorted by id. Binary search on the wrong key will return wrong answers without raising any error.
Measuring the Cost of a Search
To compare algorithms independently of hardware, this tutorial counts comparisons: how many times the algorithm compares an element (or its key) to the target. For both linear and binary search, total running time grows in proportion to this count.
Three cases matter:
- Best case: the fewest comparisons over all inputs of size
n. - Worst case: the most comparisons, often when the target is absent.
- Average case: the expected count under stated assumptions, such as "the target is present and equally likely to be at any position."
You can measure comparisons directly by wrapping the equality check:
class Counted:
comparisons = 0
def __init__(self, value):
self.value = value
def __eq__(self, other):
Counted.comparisons += 1
return self.value == other
data = [Counted(v) for v in [4, 2, 7, 1, 9]]
Counted.comparisons = 0
print(any(x == 7 for x in data), Counted.comparisons) # True 3
Counted.comparisons = 0
print(any(x == 5 for x in data), Counted.comparisons) # False 5Finding 7 took three comparisons because the scan stopped at the first match. Looking for the missing 5 took all five. That gap between a target that is present and one that is absent shows up again when the next chapters analyze linear search and compare it with binary search.
Common Mistakes When Framing a Search
- Not deciding what "not found" returns. The caller and the function each make a different assumption.
- Asking the wrong question. Calling a first-index search in a loop to collect all occurrences, when one pass would do.
- Assuming the data is sorted. Reaching for binary search on data that was sorted once and then appended to.
- Comparing the wrong thing. Using
==on floats,ison values, or Java==on strings. - Ignoring the empty collection. With
n = 0, every search must return "not found" without indexing into the collection.
Exercise
A Python helper find(a, x) returns -1 when x is missing. A caller writes print(a[find(a, x)]). For a = [10, 20, 30] and x = 99, what is printed, and how would you change the helper's contract to make this bug impossible to miss?
Show answer
It prints 30, because find returns -1 and a[-1] is the last element. Change the helper to return None (so a[None] raises TypeError immediately) or to raise ValueError like list.index. Either way the missing value fails loudly instead of quietly selecting the last element.
Exercise
For each task, name the search question from the chapter's table and say whether the scan can stop at the first match: (1) check whether a banned word appears in a comment, (2) list every line number containing "TODO", (3) find where to insert a new score into a sorted leaderboard.
Show answer
(1) Membership; it can stop at the first match. (2) All occurrences; it must examine every line. (3) Insertion point; it requires sorted data, and binary search can find it without scanning everything.
Exercise
Using the Counted class from the chapter, how many comparisons does any(x == 9 for x in data) perform on data built from [4, 2, 7, 1, 9]? What about on an empty list?
Show answer
Five comparisons, because 9 is the last element. On an empty list, it performs zero comparisons and returns False.