Skip to main content

Featured

Space Explorers Book 7: Answers and Explanations

Memunic Space Explorers › Book 7: Memoon and the Search for Another Home › Answers and Explanations Answers and Explanations Habitable means life could live there; inhabited means life does live there. A world can be habitable and empty, as an unoccupied flat has a roof and water but nobody in it. The Moon has almost no air, so water would boil or freeze, and its gravity is only about one-sixth of Earth’s, too weak to keep air. Accept also: no greenhouse blanket, so it swings between very hot and very cold. Venus. It matches Earth in size and roughly in mass, but its thick carbon dioxide air traps heat, making it hot and crushing. “Twin” is only true for size and weight. A dip of 1 per cent means (planet width divided by star width) squared is 0.01, so the ratio is 0.1: the planet is about a tenth as wide as the star. Repeats at the same gap show the planet is going round the star in 12 days, and rule out a one-time event such as a passing object. A planet shines only by reflected l...

Byte by Byte Book 7: Chapter 8 – Searching, Sorting and Efficiency

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.

  1. Look at the middle item.
  2. If it is the target, stop: found.
  3. If the target is bigger, throw away the middle item and everything to its left; search the right half.
  4. If the target is smaller, throw away the middle item and everything to its right; search the left half.
  5. 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:

Index01234567891011121314
Value3812192531404752606875839097
Steplowhighmiditems[mid]Decision
101474752 > 47, search right: low = 8
2814117552 < 75, search left: high = 10
381096052 < 60, search left: high = 8
488852Found 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 listLinear search (worst case)Binary search (worst case)
16165
1,0001,00010
1,000,0001,000,00020
2,400,0002,400,00022
1,000,000,0001,000,000,00030

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.

  1. 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 passList
Start29, 10, 14, 37, 13
110, 14, 29, 13, 37
210, 14, 13, 29, 37
310, 13, 14, 29, 37
4No 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.

  1. Selection sort. Find the smallest item in the unsorted part and swap it into the first

unsorted position. Repeat for the rest.

After stepList (sorted part in bold)
Start29, 10, 14, 37, 13
110, 29, 14, 37, 13
210, 13, 14, 37, 29
310, 13, 14, 37, 29
410, 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
  1. 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 insertingList (sorted part in bold)
Start29, 10, 14, 37, 13
1010, 29, 14, 37, 13
1410, 14, 29, 37, 13
3710, 14, 29, 37, 13
1310, 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.

AlgorithmIdeaGood atWeak at
Bubble sortSwap neighbours until no swapsEasy to understand; fast if the list is nearly sortedVery slow on large, jumbled lists
Selection sortRepeatedly select the smallestFew swaps (at most one per step)Always makes about the same number of comparisons, even if already sorted
Insertion sortInsert each item into a growing sorted partSmall or nearly sorted lists; sorting data as it arrivesSlow on large, jumbled lists
Timsort (Python) and merge sortDivide the list, sort the parts, merge themLarge listsMore 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 growExampleDoubling the data...
ConstantLooking 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.

Illustration from Byte by Byte Book 7: Chapter 8 – Searching, Sorting and Efficiency

🛠️ 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:

TargetLinear stepsBinary 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

  1. What is the difference between linear search and binary search? Which one needs a sorted list?
  2. Trace a binary search for 19 in the 15-number list in this chapter. Show low, high and mid at each step.
  3. 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.)
  4. Why does linear_search return −1 when the target is missing?
  5. Show the list [8, 3, 6, 1] after each pass of bubble sort.
  6. Show the list [8, 3, 6, 1] after each step of selection sort.
  7. Which simple sort would you choose for a list that is already almost in order, and why?
  8. If a list doubles in size, roughly how much longer does each of these take: linear search, binary search, bubble sort?
  9. Use the greedy method to pay ₹143 with the fewest notes and coins from ₹100, ₹50, ₹20, ₹10, ₹5, ₹2, ₹1.
  10. Convert 66 to base 3, and convert (1022)₃ to decimal.
  11. True or false: you should always sort a list before searching it. Explain your answer.
  12. 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.

Watch this chapter on YouTube

Comments

Popular posts from this blog

CA-7 Job Status and Failure Reason Codes

Here are the various status codes that You may see for jobs in the Queue or Logs in CA-7. R-C0002 R-C0003 R-C0099 R-C0255 R-JCLER A-U0002 A-U0004 A-U0015 A-U0043 A-U4095 A-SOC7 A-U4000 Reason Code/Job Status Code explanation: The indication of the job's current disposition. Values and their meanings are: A-Snnnn-- The job has failed with a system abend. A-Unnnn --The job has failed with a user abend. C-Cnnnn --The job has completed successfully and is going through completion processing. E-ARFATT-- An error occurred during the attempt to attach ARF definitions. This can result if the ARFSET specified is not defined. A diagnostic message may have been written to the CA-7 log, the OS console, or to the trailer queue for the job (in which case it can be displayed using LQ,JOB=x,LIST=ALL). E-ARFERR ---The job encountered an error in the ARF processing. Do a LARFQ command for the job to get more specific information. E-SEGERR --The job has been requeued...

Whistling Winds and Waterfalls: 4 Days of Magic in Shillong

Nestled in the clouds, where the scent of pine trees mingles with the rhythm of waterfalls and the tunes of local guitar-strumming youth—Shillong is more than a place. It’s a vibe. If you’ve got 3 nights and 4 days, you’ve got just enough time to fall in love. Here’s how to make the most of it—food, fun, fog and fantastic views included. Day 1: Shillong, We’re Coming for You! You land in Guwahati, barely out of the airport when the hills start calling. You hop into your cab, Spotify on, windows down, and the three-hour ride to Shillong begins. Just when you think it can’t get better, you stop at Umiam Lake —a lake so calm, it looks like someone ironed the water. By evening, you’re sipping hot chai in Laitumkhrah, maybe nibbling on spicy momos or pork jadoh from a roadside stall. You’re checked into your charming hotel ( Tripura Castle if you fancy old-world royalty, Ri Kynjai if you’re into lakeside poetry). The breeze whispers secrets of waterfalls and pine forests. Sleep well, drea...

Installing and Configuring Hadoop on Ubuntu as a Pseudo Distributed Single Node Cluster

Briefly what is psuedo-distributed single node Hadoop cluster: It is a Hadoop distributed cluster having Single Node. All the five daemons (NN,DN,JT,TT,SNN) are running as individual JVM (java process) instances. We will get all distributed features of Hadoop. This mode is used to develop, test, and staging (before production) Map Reduce programs quickly. It writes all the system, daemon and user logs to different files on the cluster To install Hadoop in this mode, we have to modify the hadoop-env.sh, core-site.xml, hdfs-site.xml, mapred-site.xml. hadoop-env.sh contains all the Environment variables which are required for running Hadoop. All the default values are fine, Only we have to modify the JAVA_HOME=“The location of Java Home Directory” Core-site.xml contains all the cluster specific information like io, temp directory, sorting, file system uri etc. Hdfs-site.xml contains all the parameters which are specific to HDFS like name node directory, data node directory...