Byte by Byte › Book 7: Networks, Programming and Machine Learning › Chapter 8: Searching, Sorting and Efficiency
Chapter 8: Searching, Sorting and Efficiency
You will learn: how linear search and binary search work and when each can be used, three classic sorting algorithms (bubble, selection and insertion sort), how to trace them by hand, how to compare algorithms by counting steps, why efficiency matters with large data, how to solve simple optimisation problems, and how to convert numbers into any base.
🔎 The Case
The connection log was a single file of 2,400,000 lines, one for every login to the Light Bridges in the past month. Each line held a time, an account name and the network address it had connected from, in the order they had happened.
Memoon's first program was simple. Start at line one. Is this the_looking_glass ? No. Line two? No. Line three...
It had found nothing after ten minutes because, it turned out, she had told it to print every line it checked, and printing is slow. Without the printing it took a fraction of a second, which felt like a victory until Frost explained the problem.
"The hub doesn't have one question," he said. "It has thousands. Every time anyone logs in, every time a message is routed, the hub has to look something up. If every lookup checks every line, the Light Bridges grind to a halt." He tapped the screen. "Searching one thing in a big pile is easy. Searching quickly, a thousand times a second, is the real skill."
Vega had a pack of numbered cards from somewhere. She shuffled them, spread them face down and said, "Find the 52. Go."
Memoon turned them over one by one. It took her eleven cards.
Vega gathered them up, sorted them, laid them face down in order and said, "Again."
This time Memoon turned over the middle card. Then she smiled.
💡 The Concepts
What is an algorithm, again? An algorithm is a precise, step-by-step method for solving a problem (Book 2). Many different algorithms can solve the same problem. They all give the right answer, but some take far more steps than others. Computer scientists study which algorithm is best for which job. Two of the most common jobs are searching (finding an item) and sorting (putting items in order).
Linear search. A linear search (or sequential search) checks each item in turn, from the start, until it finds the target or reaches the end.
def linear_search(items, target):
"""Return the index of target in items, or -1 if it is not there."""
for i in range(len(items)):
if items[i] == target:
return i
return -1
Returning −1 is a common way to say "not found", because −1 can never be a real index found by counting up from 0.
- Advantage: it works on any list, sorted or not, and is simple to write.
- Disadvantage: in the worst case (the item is last, or missing) it checks every item. For a list of n items, that is n comparisons. A list of 2,400,000 items may need 2,400,000 checks.
Binary search. A binary search works only on a sorted list, but it is dramatically faster. It is the method you use with a printed dictionary.
- Look at the middle item.
- If it is the target, stop: found.
- If the target is bigger, throw away the middle item and everything to its left; search the right half.
- If the target is smaller, throw away the middle item and everything to its right; search the left half.
- Repeat on the remaining half until you find the target or nothing is left (not found).
Each step throws away half of what remains. That is the idea of divide and conquer.
def binary_search(items, target):
"""Return the index of target in the SORTED list items, or -1."""
low = 0
high = len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Tracing a binary search. Search for 52 in this sorted list of 15 numbers:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Value | 3 | 8 | 12 | 19 | 25 | 31 | 40 | 47 | 52 | 60 | 68 | 75 | 83 | 90 | 97 |
| Step | low | high | mid | items[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 14 | 7 | 47 | 52 > 47, search right: low = 8 |
| 2 | 8 | 14 | 11 | 75 | 52 < 75, search left: high = 10 |
| 3 | 8 | 10 | 9 | 60 | 52 < 60, search left: high = 8 |
| 4 | 8 | 8 | 8 | 52 | Found at index 8 |
Four comparisons instead of nine. Searching for a missing number such as 5 also takes just 4 steps before low passes high and the function returns −1.
How much faster? Each step halves the list, so the number of steps is how many times you can halve n before reaching 1: about log₂ n, the power of 2 that gives n. You met powers of 2 in Book 6: 2¹⁰ = 1,024, so a sorted list of 1,000 items needs at most 10 steps.
| Items in the list | Linear search (worst case) | Binary search (worst case) |
|---|---|---|
| 16 | 16 | 5 |
| 1,000 | 1,000 | 10 |
| 1,000,000 | 1,000,000 | 20 |
| 2,400,000 | 2,400,000 | 22 |
| 1,000,000,000 | 1,000,000,000 | 30 |
Doubling the size of the list doubles the work for linear search but adds only one step for binary search.
The catch: binary search needs sorted data. Sorting takes time too. If you search a list only once, a linear search may be quicker overall. If you search it thousands of times, sorting it once and then using binary search wins easily. Databases and search engines keep their data sorted, or build sorted indexes (Book 6), for exactly this reason.
Sorting algorithms. Python's sort() and sorted() (Chapter 5) use a fast, clever algorithm called Timsort. To understand what sorting involves, every programmer learns three simple algorithms first. We will sort the list [29, 10, 14, 37, 13] with each.
- Bubble sort. Go through the list comparing each pair of neighbours. If they are in the
wrong order, swap them. One complete trip through the list is called a pass. After each pass, the largest remaining item has "bubbled up" to its correct place at the end. Repeat until a pass makes no swaps.
| After pass | List |
|---|---|
| Start | 29, 10, 14, 37, 13 |
| 1 | 10, 14, 29, 13, 37 |
| 2 | 10, 14, 13, 29, 37 |
| 3 | 10, 13, 14, 29, 37 |
| 4 | No swaps: sorted |
def bubble_sort(items):
"""Return a sorted copy of items using bubble sort."""
items = items.copy()
n = len(items)
for p in range(n - 1):
swapped = False
for i in range(n - 1 - p):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
if not swapped:
break
return items
The line items[i], items[i + 1] = items[i + 1], items[i] swaps two values in one go, using the tuple packing you met in Chapter 6. The swapped flag lets the sort stop early once the list is in order.
- Selection sort. Find the smallest item in the unsorted part and swap it into the first
unsorted position. Repeat for the rest.
| After step | List (sorted part in bold) |
|---|---|
| Start | 29, 10, 14, 37, 13 |
| 1 | 10, 29, 14, 37, 13 |
| 2 | 10, 13, 14, 37, 29 |
| 3 | 10, 13, 14, 37, 29 |
| 4 | 10, 13, 14, 29, 37 |
def selection_sort(items):
"""Return a sorted copy of items using selection sort."""
items = items.copy()
n = len(items)
for i in range(n - 1):
smallest = i
for j in range(i + 1, n):
if items[j] < items[smallest]:
smallest = j
items[i], items[smallest] = items[smallest], items[i]
return items
- Insertion sort. Build a sorted part one item at a time. Take the next item, and slide it left
past every bigger item until it sits in its correct place, as you would sort a hand of playing cards.
| After inserting | List (sorted part in bold) |
|---|---|
| Start | 29, 10, 14, 37, 13 |
| 10 | 10, 29, 14, 37, 13 |
| 14 | 10, 14, 29, 37, 13 |
| 37 | 10, 14, 29, 37, 13 |
| 13 | 10, 13, 14, 29, 37 |
def insertion_sort(items):
"""Return a sorted copy of items using insertion sort."""
items = items.copy()
for i in range(1, len(items)):
current = items[i]
j = i - 1
while j >= 0 and items[j] > current:
items[j + 1] = items[j]
j = j - 1
items[j + 1] = current
return items
Comparing the sorts.
| Algorithm | Idea | Good at | Weak at |
|---|---|---|---|
| Bubble sort | Swap neighbours until no swaps | Easy to understand; fast if the list is nearly sorted | Very slow on large, jumbled lists |
| Selection sort | Repeatedly select the smallest | Few swaps (at most one per step) | Always makes about the same number of comparisons, even if already sorted |
| Insertion sort | Insert each item into a growing sorted part | Small or nearly sorted lists; sorting data as it arrives | Slow on large, jumbled lists |
| Timsort (Python) and merge sort | Divide the list, sort the parts, merge them | Large lists | More complex to write |
All three simple sorts make roughly n × n ÷ 2 comparisons on a jumbled list of n items. For 1,000 items that is about 500,000 comparisons; for 1,000,000 items, about 500 billion. Divide-and-conquer sorts such as merge sort need only about n × log₂ n: about 20 million for a million items, which is around 25,000 times fewer.
Efficiency. The efficiency of an algorithm is how its time (or memory) grows as the input grows. Computer scientists describe it with Big O notation, which you will study properly later. For now, the idea is enough:
| How the steps grow | Example | Doubling the data... |
|---|---|---|
| Constant | Looking up a list item by index, or a dictionary key | ...takes the same time |
| Logarithmic (log n) | Binary search | ...adds one step |
| Linear (n) | Linear search; summing a list | ...doubles the time |
| Quadratic (n × n) | Bubble, selection, insertion sort | ...four times the time |
This is also why Chapter 7's dictionaries are so useful: Python finds a dictionary key in roughly constant time, however many keys there are, using a clever technique called hashing (related to the hashes in Chapter 3).
Optimisation problems. An optimisation problem asks for the best solution: the maximum or minimum of something, within rules (constraints). The CBSE Computational Thinking curriculum is full of them. A simple and powerful method is the greedy algorithm: at each step, take the choice that looks best right now.
Example: give ₹87 in change using the fewest coins and notes from ₹50, ₹20, ₹10, ₹5, ₹2 and ₹1. Greedy: take the largest that fits each time: 50 (37 left), 20 (17 left), 10 (7 left), 5 (2 left), 2 (0 left). Five pieces, which is the minimum.
Greedy is fast, but it is not always right. With coins of ₹1, ₹3 and ₹4, greedy pays ₹6 as 4 + 1 + 1 (three coins), but 3 + 3 (two coins) is better. When greedy fails, an algorithm may have to try every possibility (brute force, as in Chapter 3), or use cleverer methods you will meet in later years.
Number systems in any base. In Book 6 you converted between decimal, binary, octal and hexadecimal. The same idea works for any base: base n uses the digits 0 to n − 1, and each place is worth n times the place to its right. Ternary (base 3) uses 0, 1 and 2 with place values 1, 3, 9, 27, 81, and so on: 55 = 2 × 27 + 0 × 9 + 0 × 3 + 1 × 1, so 55 in base 3 is 2001.
The repeated-division method you learned for binary works for every base: divide by the base, write down the remainder, repeat with the quotient, and read the remainders from bottom to top. As an algorithm:
def to_base(n, base):
"""Return n (a whole number) written in the given base (2 to 10) as a
string."""
if n == 0:
return "0"
digits = ""
while n > 0:
digits = str(n % base) + digits
n = n // base
return digits
print(to_base(55, 2), to_base(55, 3), to_base(100, 3))
print(int("2001", 3))
Output:
110111 2001 10201 55
Python's int(text, base) converts the other way, from any base back to decimal.
Career Spotlight: Algorithm engineer. Search engines, map apps, delivery companies and stock exchanges all depend on algorithms that are fast enough for billions of operations. Algorithm engineers design them, prove they are correct, and measure their efficiency. Many began with puzzles and competitive programming, such as the Indian Computing Olympiad.

🛠️ Build It
Save the functions above in a module searching.py (Chapter 6), with assert tests under if __name__ == "__main__": . Then try these activities.
Activity 1: Count the steps. Change linear_search and binary_search so each also counts its comparisons and returns them with the index, like return i, steps . Test them on list(range(1, 1001)) , searching for 1, 500, 1000 and 2000. Copy this table and fill it in:
| Target | Linear steps | Binary steps |
|---|
1
500
1000
2000
Which target is the best case for linear search? Which is the worst?
Activity 2: Race the searches. Use the time module to time both searches on a list of 2,400,000 numbers:
import time from searching import linear_search, binary_search
big = list(range(2_400_000))
start = time.perf_counter()
linear_search(big, 2_399_999)
print(f"Linear: {time.perf_counter() - start:.5f} seconds")
start = time.perf_counter()
binary_search(big, 2_399_999)
print(f"Binary: {time.perf_counter() - start:.5f} seconds")
(The underscores in 2_400_000 are allowed in Python numbers to make them easier to read.) On a typical laptop, the linear search takes a few hundredths of a second and the binary search a few millionths: thousands of times faster. Write down your own results. Why might they be different on another computer?
Activity 3: Watch the sorts. Add a print(items) line at the end of each pass in your bubble sort and run it on [29, 10, 14, 37, 13] . Do the same for selection and insertion sort. Check your output matches the tables above. Then sort [5, 4, 3, 2, 1] (the worst case) and [1, 2, 3, 5, 4] (nearly sorted) with bubble sort and count the passes.
Activity 4: Sort records. Using the list-of-dictionaries accounts from Chapter 7, write sort_by_followers(accounts) that returns the accounts sorted from most to fewest followers, by adapting your selection sort to compare items[j] ["followers"] . Check your answer against Python's own version: sorted(accounts, key=lambda a: a["followers"], reverse=True) . (A lambda is a tiny function written in one line; here it tells sorted() which value to compare.)
Activity 5: Change-maker. Write make_change(amount, coins) that uses the greedy method to return a list of the coins used. Test it with make_change(87, [50, 20, 10, 5, 2, 1]) and make_change(6, [4, 3, 1]) . Explain why the second answer is not the best.
Unplugged: Sorting race. Make three teams of six, each with the same jumbled set of number cards. Each team sorts by a different algorithm (bubble, selection or insertion), following the rules strictly: only neighbours may swap in bubble sort, and so on. A referee counts every comparison. Which team made the fewest comparisons? Which made the fewest swaps? Then try binary search: one person thinks of a number from 1 to 100 and answers only "higher", "lower" or "yes". Can you always guess it in 7 tries? Why 7? (Hint: 2⁷ = 128.)
✅ Case Closed
Memoon sorted the 2.4 million log entries by account name, once. It took a few seconds. After that, every question took a fraction of a millisecond. She ran her binary search for the_looking_glass .
Found, in 22 steps.
The account had logged in exactly once, on 30 September, from an address inside Riverbend. Vega checked the hub's routing records: that address did not belong to a home. It belonged to a small server in the back room of an old warehouse by the river. And that server was busy. It hosted a website.
Memoon opened it.
The page that appeared made everyone at the desk go quiet. It had the same deep green header as The Memunic Times. The same elegant fonts. The same layout, the same little heron in the corner, the same "Breaking News" banner. The name at the top was The Memunic Mirror, and you had to look twice to notice it was not Times.
The top story said: GUARDIAN SIMBHA: NEW PHOTOS EMERGE.
"Most people only glance at the top of a page," said Vega. "They'd swear they'd read this in the Times."
Memoon sent the link to Editor Quill. The tall grey heron arrived at Snowpeak within the hour, his green waistcoat buttoned wrong in his hurry, and stood in front of the screen trembling with fury.
"They've stolen our face," he said. "Our colours, our fonts, our whole look. How is that even possible?"
"Because a website's look is just code," said Memoon slowly. "A few lines of styling. Anyone can copy it." She thought for a moment. "Which means anyone can learn to read it, too."
❓ Test Yourself
- What is the difference between linear search and binary search? Which one needs a sorted list?
- Trace a binary search for 19 in the 15-number list in this chapter. Show low, high and mid at each step.
- A sorted list has 4,000 items. What is the greatest number of comparisons a binary search would need? (Hint: 2¹¹ = 2,048 and 2¹² = 4,096.)
- Why does
linear_searchreturn −1 when the target is missing? - Show the list
[8, 3, 6, 1]after each pass of bubble sort. - Show the list
[8, 3, 6, 1]after each step of selection sort. - Which simple sort would you choose for a list that is already almost in order, and why?
- If a list doubles in size, roughly how much longer does each of these take: linear search, binary search, bubble sort?
- Use the greedy method to pay ₹143 with the fewest notes and coins from ₹100, ₹50, ₹20, ₹10, ₹5, ₹2, ₹1.
- Convert 66 to base 3, and convert (1022)₃ to decimal.
- True or false: you should always sort a list before searching it. Explain your answer.
- Challenge: Write a program that generates a list of 2,000 random numbers, sorts a copy with your insertion sort and another copy with
sorted(), checks the two results are equal, and prints how long each took. Explain the difference.
📚 Key Terms
- Algorithm: a precise step-by-step method for solving a problem.
- Linear (sequential) search: checking each item in turn until the target is found.
- Binary search: repeatedly halving a sorted list to find a target.
- Divide and conquer: solving a problem by splitting it into smaller parts.
- Index (in data): a sorted structure used to find records quickly.
- Bubble sort: sorting by repeatedly swapping neighbours that are out of order.
- Pass: one complete trip through a list.
- Swap: exchanging the positions of two items.
- Selection sort: sorting by repeatedly selecting the smallest remaining item.
- Insertion sort: sorting by inserting each item into its place in a growing sorted part.
- Merge sort: a divide-and-conquer sort that sorts halves and merges them.
- Efficiency: how an algorithm's time or memory grows as its input grows.
- Big O notation: a way of describing an algorithm's efficiency.
- Optimisation problem: finding the best solution within given constraints.
- Greedy algorithm: an algorithm that makes the best-looking choice at each step.
- Ternary: the base-3 number system, using the digits 0, 1 and 2.
- Lambda: a small one-line function without a name.
Keep learning with Byte by Byte
Explore Book 7: Networks, Programming and Machine Learning. Find the ebook, purchase details and teaching slides on MemuniCity.
Comments
Post a Comment