MGU Computer Science Series — CS Foundations
Part III: Data and Algorithms
Linear Search · Binary Search · Selection Sort · Insertion Sort · Big-O
Chapter 12 of 28
MGU Computer Science Series  ·  Computer Science Foundations  ·  Library Textbook Edition

Chapter 12:
Searching, Sorting,
and Efficiency

Linear search, binary search, selection sort, insertion sort, input size, running time, and Big-O intuition — the tools for reasoning about how fast algorithms scale

■ Part III: Data and Algorithms ■

■ 10 Sections  •  Chapter 12 of 28 ■

Follows Chapter 11: Data Structures at an Introductory Level  ·  Prepares for Chapter 13: Abstraction, Models, and Simulation

Purpose and Overview

Every day, software searches through enormous collections of data and arranges it into useful order. Search engines scan billions of web pages. Hospitals retrieve patient records in an instant. E-commerce platforms sort products by price, rating, or relevance. Music services find songs in libraries of millions of tracks. These tasks look simple from the outside, but solving them well requires careful thinking about how an algorithm works — not just whether it works.

This chapter introduces the two most fundamental algorithmic tasks in computing — searching and sorting — and the discipline of thinking carefully about efficiency: how long an algorithm takes and how much memory it uses as data grows. Students will trace algorithms step by step, compare strategies, and develop intuition for why some approaches are dramatically faster than others.

Opening Question

Imagine a library with ten thousand books arranged in no particular order. To find a specific title, you would have to check every book until you happened upon it. Now imagine those same books arranged alphabetically. You could open to the middle, decide whether your author comes earlier or later, keep dividing — and reach the right book in a dozen steps rather than thousands. That difference is what this chapter is about.

10Sections
4Algorithms
20+Key Terms
12+Worked Examples

Learning Objectives

  1. 1Explain why searching and sorting are fundamental algorithmic tasks in computing.
  2. 2Trace linear search step by step and identify its worst-case behavior.
  3. 3Trace binary search step by step and explain why it requires sorted input.
  4. 4Compare linear search and binary search on the same dataset.
  5. 5Trace selection sort pass by pass, showing how the sorted region grows.
  6. 6Trace insertion sort step by step, showing each insertion into the sorted region.
  7. 7Explain what input size means and how running time can grow with it.
  8. 8Distinguish best-case, worst-case, and average-case behavior.
  9. 9Read Big-O notation and place algorithms within common complexity categories.
  10. 10Describe real-world efficiency tradeoffs in systems that search and sort data.

Sections at a Glance

Sections 12.1 – 12.3
Searching: Finding What You Need
Why It Matters · Linear Search · Binary Search

Why Searching and Sorting Matter

Searching and sorting sit at the core of almost everything computers do. Databases search records. Operating systems search directories. GPS applications search maps. Social networks search connections. Compilers search for variable names. Every one of these tasks is faster when the right algorithm is applied to the right data structure.

Understanding searching and sorting introduces a fundamental insight: two algorithms can both produce the correct answer, but one can be dramatically more efficient than the other. In computer science, correctness is necessary but not sufficient. A correct algorithm that takes a year to finish is not useful. Efficiency matters.

The Core Insight

Organization makes searching faster. And the choice of algorithm determines how much faster. The same principle applies to sorting: the choice of strategy determines both whether you get the right answer and how long it takes to get there.

What This Chapter Covers

TopicAlgorithmsKey Question
SearchingLinear search, Binary searchHow do we find a specific item in a collection?
SortingSelection sort, Insertion sortHow do we rearrange a collection into a defined order?
EfficiencyBig-O intuitionHow does running time grow as data grows?

Linear Search

The simplest possible search strategy is also the most honest: check every item, one at a time, until you find what you are looking for — or until you have checked everything and confirmed it is not there. This approach is called linear search, sometimes also called sequential search. It is linear because the algorithm moves through the list in a straight line from beginning to end.

How Linear Search Works

Suppose you have a list of student ID numbers and want to find whether 40217 appears in it:

List: [38412, 41009, 22874, 40217, 51003, 19338, 60021] Target: 40217
  1. Step 1Position 0. Is 38412 equal to 40217? No. Move on.
  2. Step 2Position 1. Is 41009 equal to 40217? No. Move on.
  3. Step 3Position 2. Is 22874 equal to 40217? No. Move on.
  4. Step 4Position 3. Is 40217 equal to 40217? Yes. Return position 3.

Pseudocode: Linear Search

ALGORITHM LinearSearch(list, target): FOR each position i FROM 0 TO length(list) - 1: IF list[i] equals target: RETURN i RETURN -1 # -1 indicates "not found"

Python-Style Example

def linear_search(items, target): for i in range(len(items)): if items[i] == target: return i return -1 scores = [88, 72, 95, 61, 79, 84, 55] result = linear_search(scores, 79) if result == -1: print("Not found.") else: print("Found at position", result) # Output: Found at position 4

When Linear Search Is Fast and When It Is Not

SituationSteps Required
Target is the first item1 step
Target is in the middleAbout n/2 steps
Target is the last itemn steps
Target is not in the listn steps — must check everything
When Linear Search Makes Sense

Use linear search when the list is unsorted and cannot easily be sorted first, when the list is small enough that checking every item is fast, when data changes frequently making presorting impractical, or when you need to find all occurrences of an item rather than just the first.

Binary Search

If a list is already sorted, a much faster strategy becomes possible. Instead of checking items one by one from the beginning, you can start in the middle of the list and eliminate half the remaining candidates with a single comparison. This is binary search. Each step cuts the remaining search space in half.

Example 12.3.1
Tracing binary search for target 88
  • SetupSorted list: [14, 22, 35, 47, 61, 73, 88, 95, 102]
    Indices:     0   1   2   3   4   5   6   7    8
  • Step 1low=0, high=8. mid=4. list[4]=61. Is 88 > 61? Yes → set low=5.
  • Step 2low=5, high=8. mid=6. list[6]=88. Is 88 == 88? Yes. Return 6.
Answer: Found at index 6 in only 2 comparisons.

Pseudocode: Binary Search

ALGORITHM BinarySearch(list, target): low ← 0 high ← length(list) - 1 WHILE low is less than or equal to high: mid ← (low + high) divided by 2 # integer division IF list[mid] equals target: RETURN mid ELSE IF target is greater than list[mid]: low ← mid + 1 # search right half ELSE: high ← mid - 1 # search left half RETURN -1 # not found

Python-Style Example

def binary_search(items, target): low = 0 high = len(items) - 1 while low <= high: mid = (low + high) // 2 # // is integer division if items[mid] == target: return mid elif target > items[mid]: low = mid + 1 else: high = mid - 1 return -1 temperatures = [12, 18, 23, 27, 31, 35, 38, 42, 47] result = binary_search(temperatures, 35) print("Found at position", result) # Output: Found at position 5
Critical Requirement: The List Must Be Sorted

Binary search only works correctly on a sorted list. If the list is unsorted, eliminating half the candidates based on a comparison is not valid — the target could be anywhere. Before applying binary search, you must confirm the data is sorted or sort it first. An unsorted list may cause binary search to return -1 (not found) even when the item is present.

Comparing the Two Search Strategies

PropertyLinear SearchBinary Search
Requires sorted list?NoYes
Worst-case stepsn (all items)about log₂(n)
Steps for 1,000 itemsUp to 1,000Up to 10
Steps for 1,000,000 itemsUp to 1,000,000Up to 20
Good for unsorted data?YesNo
Good for large sorted data?NoYes
What Is log₂(n)?

The number log₂(n) means "how many times you can divide n by 2 before reaching 1." For one million items, log₂(1,000,000) ≈ 20. Binary search takes at most 20 steps where linear search might take one million. That difference is enormous — and grows larger with every doubling of the dataset.

Sections 12.4 – 12.6
Sorting: Putting Things in Order
Sorting as Organization · Selection Sort · Insertion Sort

Sorting as Organization

Searching is easier when data is sorted. Databases, file systems, dictionaries, phone books, spreadsheets, and libraries all depend on sorted data for efficient retrieval. Sorting means rearranging a collection of items so that they appear in a defined order — numerical, alphabetical, chronological, or by any computed property.

Why is sorting non-trivial? A computer algorithm can only compare two items at a time and then make a decision. Every sorting algorithm is built from many small two-item comparisons. The question is: in what order do you make those comparisons, and what do you do with the results? Different answers produce different algorithms with different efficiency characteristics.

What Correct Sorting Must Guarantee

Completeness: Every item in the original list appears in the sorted list.

Order: Every adjacent pair in the result satisfies the target ordering.

No duplication: Items are rearranged, not added or removed.

Selection Sort

Selection sort is one of the simplest sorting algorithms to understand and trace. The idea is intuitive: repeatedly find the smallest remaining item and move it to its correct position. Once an item is placed, it never moves again.

Example 12.5.1
Tracing selection sort on [64, 25, 12, 22, 11]
  • Pass 1Find minimum of entire list: 11 (index 4). Swap with index 0.
    [11, 25, 12, 22, 64] — position 0 is now permanent.
  • Pass 2Find minimum of positions 1–4: 12 (index 2). Swap with index 1.
    [11, 12, 25, 22, 64] — positions 0–1 permanent.
  • Pass 3Find minimum of positions 2–4: 22 (index 3). Swap with index 2.
    [11, 12, 22, 25, 64] — positions 0–2 permanent.
  • Pass 4Find minimum of positions 3–4: 25 already at index 3. No swap.
    [11, 12, 22, 25, 64]
  • DoneOne item remains. Sorted: [11, 12, 22, 25, 64]
Answer: 4 passes, 10 comparisons total. Always the same regardless of initial order.

Pseudocode: Selection Sort

ALGORITHM SelectionSort(list): n ← length(list) FOR i FROM 0 TO n - 2: min_index ← i FOR j FROM i + 1 TO n - 1: IF list[j] is less than list[min_index]: min_index ← j IF min_index does not equal i: Swap list[i] and list[min_index]

Python-Style Example

def selection_sort(items): n = len(items) for i in range(n - 1): min_index = i for j in range(i + 1, n): if items[j] < items[min_index]: min_index = j if min_index != i: items[i], items[min_index] = items[min_index], items[i] return items data = [64, 25, 12, 22, 11] print(selection_sort(data)) # Output: [11, 12, 22, 25, 64]

Tracing Table: Selection Sort

PassList StateAction
Start[64, 25, 12, 22, 11]Unsorted
1[11, 25, 12, 22, 64]Swapped 11 and 64
2[11, 12, 25, 22, 64]Swapped 12 and 25
3[11, 12, 22, 25, 64]Swapped 22 and 25
4[11, 12, 22, 25, 64]No swap needed
Done[11, 12, 22, 25, 64]Sorted ✓
Key Property of Selection Sort

Selection sort always makes the same number of comparisons regardless of how the data is arranged. Even on an already-sorted list, it scans every remaining item to confirm the minimum. This predictability is both its strength (guaranteed behavior) and its weakness (no shortcut for easy inputs).

Insertion Sort

Insertion sort works differently. Instead of finding the minimum on each pass, it takes one item at a time from the unsorted portion and inserts it into the correct position within the already-sorted portion. Think of the way many people sort a hand of playing cards: you pick up one card at a time and slide it into the right position among the cards you are already holding.

Example 12.6.1
Tracing insertion sort on [5, 2, 8, 1, 9, 3]
  • StartSorted region: [5]. Unsorted: [2, 8, 1, 9, 3]
  • Insert 22 < 5 → shift 5 right. Insert 2 before it.
    [2, 5, 8, 1, 9, 3]
  • Insert 88 > 5 → no shifting. 8 stays in place.
    [2, 5, 8, 1, 9, 3]
  • Insert 11 < 8, < 5, < 2 → shift all three right. Insert 1 at position 0.
    [1, 2, 5, 8, 9, 3]
  • Insert 99 > 8 → no shifting. 9 appended after 8.
    [1, 2, 5, 8, 9, 3]
  • Insert 33 < 9, < 8, < 5 → shift those three. 3 > 2 → insert after 2.
    [1, 2, 3, 5, 8, 9]
Answer: [1, 2, 3, 5, 8, 9]

Pseudocode: Insertion Sort

ALGORITHM InsertionSort(list): FOR i FROM 1 TO length(list) - 1: key ← list[i] j ← i - 1 WHILE j is greater than or equal to 0 AND list[j] is greater than key: list[j + 1] ← list[j] j ← j - 1 list[j + 1] ← key

Python-Style Example

def insertion_sort(items): for i in range(1, len(items)): key = items[i] j = i - 1 while j >= 0 and items[j] > key: items[j + 1] = items[j] j -= 1 items[j + 1] = key return items data = [5, 2, 8, 1, 9, 3] print(insertion_sort(data)) # Output: [1, 2, 3, 5, 8, 9]
When Insertion Sort Is Especially Fast

If the list is already sorted, the inner while loop never executes. Each new item is larger than everything already sorted, so it just gets appended at the end. In that case, insertion sort completes in only n comparisons — much faster than selection sort on the same data. This makes insertion sort ideal for lists that are already sorted or nearly sorted, and for online settings where items arrive one at a time.

Sections 12.7 – 12.8
Comparing Algorithms and Reasoning About Scale
Algorithm Comparison · Input Size · Running Time · Best / Worst / Average Case

Comparing Algorithms

Search Algorithm Comparison

Consider a sorted list of one million items. With linear search, the worst case requires checking all one million items. With binary search, the worst case requires at most 20 comparisons, since 2²⁰ = 1,048,576. The table below makes this concrete.

Items in ListLinear Search (worst case)Binary Search (worst case)
1010 comparisons4 comparisons
100100 comparisons7 comparisons
1,0001,000 comparisons10 comparisons
1,000,0001,000,000 comparisons20 comparisons
1,000,000,0001,000,000,000 comparisons30 comparisons

Sorting Algorithm Comparison

SituationSelection SortInsertion Sort
Already sortedStill does all comparisonsVery fast — O(n) comparisons
Reverse sortedFull workFull work — worst case
Random orderFull workAbout half of worst case
Both Sorting Algorithms Have Limits at Scale

Selection sort and insertion sort are both called O(n²) algorithms. For a list of 10,000 items, that means roughly 100,000,000 comparisons in the worst case. More efficient algorithms — mergesort, quicksort, heapsort — can sort n items in O(n log n) time. Those are covered in later courses. For now, the key insight is: algorithm design choices have profound consequences as data scales up.

Input Size and Running Time

One of the most important ideas in algorithm analysis is that the relationship between input size and running time determines how well an algorithm scales. Input size is usually measured as the number of items being processed — conventionally written as n. Running time is the number of basic operations the algorithm performs.

The critical question is not "how fast is this algorithm on my current data?" but rather: how does running time grow as n grows?

A Growth Rate Illustration

nAlgorithm A — n stepsAlgorithm B — n² stepsAlgorithm C — 2ⁿ steps
1000.001 sec0.001 secVastly longer than universe age
1,0000.01 sec0.1 secImpossible in practice
10,0000.1 sec10 secImpossible in practice
1,000,00010 sec11.6 daysImpossible in practice

Algorithm C with 2ⁿ steps becomes completely impractical even for modest input sizes. This illustrates why growth rate dominates over constant factors: an algorithm that does 100·n operations will eventually outperform one that does n² operations, because n² grows much faster than 100n as n increases. Specifically, 100n < n² whenever n > 100.

Best Case, Worst Case, and Average Case

CategoryDescriptionExample
Best caseMost favorable input — fewest operationsLinear search finds target at position 0
Worst caseMost unfavorable input — most operationsLinear search: target absent, checks all n items
Average caseExpected behavior across typical inputsLinear search: target at middle on average
Why Worst Case Is Emphasized

Worst-case analysis provides an upper bound guarantee. You can promise a user that binary search will finish in at most 20 steps for a million-item list, regardless of where the target is. That guarantee is impossible to make from average case alone. In critical systems — databases, medical records, real-time applications — knowing the ceiling matters as much as knowing the average.

Sections 12.9 – 12.10
Big-O Intuition and Real-World Tradeoffs
Big-O Notation · Common Categories · Efficiency Tradeoffs · Real Systems

Big-O Intuition

Computer scientists use a notation called Big-O to describe the growth rate of an algorithm's running time in a standardized, precise way. The notation O(f(n)) means: as n grows large, the algorithm's running time grows no faster than a constant multiple of f(n). The function inside the notation captures the dominant growth behavior, ignoring constants and smaller terms.

Common Big-O Categories

NotationNameWhat It MeansExamples
O(1)ConstantTime does not change with input sizeArray index lookup, hash table lookup
O(log n)LogarithmicTime grows very slowly — doubles when input squaresBinary search
O(n)LinearTime grows in proportion to input sizeLinear search, scanning a list
O(n log n)LinearithmicSlightly worse than linear — efficient sortingMergesort, Timsort
O(n²)QuadraticTime grows as the square of input sizeSelection sort, insertion sort (worst)
O(2ⁿ)ExponentialDoubles for every additional item — quickly infeasibleBrute-force combinatorial problems

Placing Our Algorithms

AlgorithmBig-ONotes
Linear searchO(n)Must check up to n items in the worst case
Binary searchO(log n)Halves the search space each step; requires sorted input
Selection sortO(n²)Two nested loops over n items; always the same work
Insertion sortO(n²) worst, O(n) bestBest case on already-sorted data; depends heavily on input
Big-O Is About Growth, Not Exact Time

Big-O does not tell you exactly how many seconds an algorithm will take. It tells you how running time grows relative to input size. Two O(n) algorithms might differ by a factor of 10 in raw speed. Big-O ignores those constants. This is why algorithm analysis and hardware optimization are complementary, not interchangeable: a faster computer helps every algorithm, but a better algorithm helps even more as data grows.

Practical Rules of Thumb

  1. O(1)Ideal — aim for this with lookups and array indexing.
  2. O(log n)Excellent — binary search, balanced tree lookups.
  3. O(n)Acceptable — scanning a list once, simple data processing.
  4. O(n log n)Efficient — the best comparison-based sorting algorithms.
  5. O(n²)Acceptable only for small n — avoid on large datasets.
  6. O(2ⁿ)Impractical for n > 30 in most contexts.

Efficiency Tradeoffs in Real Systems

In real software, the choice of algorithm is never made in isolation. It is made in the context of a system with real constraints: How much data will be processed? How often will it be searched versus updated? How much memory is available? How fast must results appear? Is the data already partially sorted? These questions reveal that efficiency is not just about comparing one algorithm to another in the abstract — it is about matching algorithms to the reality of the problem.

Sort Once, Search Many Times

If a dataset is searched thousands of times but changes rarely, it is worth the cost of sorting it once in order to benefit from binary search on every subsequent lookup. A dictionary is built and sorted once; you then look up words millions of times, and every lookup is fast because the dictionary is sorted. But if data changes constantly, maintaining sorted order becomes expensive, and different data structures and indexing strategies are used instead.

Memory Use

Selection sort and insertion sort both sort the list in-place, using only a small constant amount of extra memory. Mergesort, a more efficient O(n log n) algorithm, requires additional memory proportional to the list size for temporary storage. It is faster in time but more expensive in memory. This tradeoff — trading memory for time, or time for memory — is fundamental in systems design.

Real Language: Python's Built-In Sort

Python's built-in sorted() and list.sort() use an algorithm called Timsort, which detects already-sorted runs in data and uses insertion sort for small segments while using merge sort for large ones. It takes advantage of insertion sort's best-case strength and mergesort's overall efficiency. Understanding the principles behind sorting algorithms helps you recognize why a standard library function is both safe and fast to trust.

Security: Algorithmic Complexity Attacks

Algorithm efficiency is not just a performance concern — it can become a security concern. Some servers have been attacked using algorithmic complexity attacks: the attacker sends inputs designed to trigger the worst-case behavior of a vulnerable algorithm, consuming so much CPU time that the server becomes unresponsive. Choosing algorithms whose worst case is controlled and predictable is one element of robust, secure system design.

The Larger Lesson

The study of searching and sorting is, at a deeper level, the study of a foundational question in computer science: how do we design step-by-step procedures that solve problems correctly and scale gracefully? Every topic that follows — data structures, databases, operating systems, networks, machine learning — involves algorithms that must work on real data at real scale. The habits of thought in this chapter are habits you will use throughout your computing work.

Chapter Summary

Key Terms

algorithm analysis
Studying how an algorithm's resource use (time, memory) grows with input size.
best case
The input arrangement on which an algorithm performs with the fewest operations.
Big-O notation
Written O(f(n)); describes the upper bound on an algorithm's growth rate, ignoring constants and smaller terms.
binary search
Repeatedly divides the search space in half; requires a sorted list; O(log n) worst case.
comparison
The fundamental operation in searching and sorting: deciding whether one value is less than, equal to, or greater than another.
efficiency
How well an algorithm uses computational resources relative to the size of its input.
in-place algorithm
An algorithm that rearranges data using only a small constant amount of extra memory beyond the input itself.
input size (n)
The number of items being processed; the variable against which running time is measured.
insertion sort
Builds a sorted region one item at a time, inserting each into its correct position. O(n²) worst, O(n) best case.
linear search
Checks each item in order from start to finish; works on any list; O(n) worst case.
logarithm
log₂(n) is the number of times n can be halved before reaching 1. Binary search makes at most log₂(n) comparisons.
O(1) — constant
Time does not change with input size. Ideal for lookups.
O(log n) — logarithmic
Time grows very slowly; binary search. Excellent scalability.
O(n) — linear
Time grows in proportion to n; linear search, list scanning.
O(n²) — quadratic
Time grows as the square of n; both sorting algorithms in this chapter.
precondition
A condition that must be true before an algorithm can operate correctly. Binary search requires a sorted list.
running time
The number of basic operations an algorithm performs on a given input.
selection sort
Repeatedly finds the minimum of the unsorted region and places it at the front. O(n²) time.
sorted list
A list whose items are arranged in a defined order; required precondition for binary search.
worst case
The input on which an algorithm performs the most operations; provides an upper bound guarantee.

Worked Example Review

Review Example 1
Tracing linear search for target 73 in [45, 19, 73, 88, 31, 60]
StepIndexValueMatch?
1045No
2119No
3273Yes — return 2 ✓
Found at index 2 in 3 comparisons.
Review Example 2
Tracing binary search for target 50 (not present) in [7, 15, 23, 33, 41, 55, 68, 79, 90]
Steplowhighmidlist[mid]Action
10844150 > 41 → low = 5
25866850 < 68 → high = 5
35555550 < 55 → high = 4
4low (5) > high (4) → Return -1 (not found) ✓
Not found in 4 comparisons — confirmed absent.
Review Example 3
Selection sort trace on [29, 10, 14, 37, 13]
PassMinimum FoundActionResult
110 at index 1Swap 29 and 10[10, 29, 14, 37, 13]
213 at index 4Swap 29 and 13[10, 13, 14, 37, 29]
314 at index 2No swap needed[10, 13, 14, 37, 29]
429 at index 4Swap 37 and 29[10, 13, 14, 29, 37]
Done[10, 13, 14, 29, 37] — Sorted ✓

Concept Check

  1. What does linear search require before it can be applied to a list?
  2. What does binary search require before it can be applied?
  3. If a sorted list has 1,024 items, what is the maximum number of comparisons binary search needs? (Hint: 2¹⁰ = 1,024.)
  4. What does selection sort do at each pass?
  5. What makes insertion sort faster than selection sort when the list is already sorted?
  6. What does Big-O notation describe?
  7. Which is faster at large scales: O(n) or O(n²)?
  8. Give one real-world example where sorting data first makes searching much faster.
Part AVocabulary in Context

Fill in the correct term for each statement.

  1. An algorithm with __________ time complexity does not slow down as the input grows larger.
  2. The __________ case describes the most unfavorable possible input for a given algorithm.
  3. Binary search has __________ time complexity.
  4. Selection sort and insertion sort both have __________ time complexity in their worst case.
  5. A __________ is a condition that must be true before an algorithm can operate correctly.
Part BAlgorithm Tracing
  1. Trace linear search for target 55 in [12, 44, 71, 55, 30, 82, 19]. Show each step. How many comparisons does it take?
  2. Trace binary search for target 30 in [5, 12, 20, 30, 45, 60, 75, 88, 96]. Show each step with low, high, and mid values.
  3. Trace selection sort on [8, 3, 7, 1, 5]. Show the list after each complete pass.
  4. Trace insertion sort on [4, 6, 2, 9, 1]. Show the list after each item is inserted into the sorted region.
Part CComparison and Analysis
  1. A list has 512 items and is sorted. How many comparisons does linear search need in the worst case? How many does binary search need? What is the ratio?
  2. Explain why binary search cannot be used on [10, 50, 20, 40, 30] to find the value 40. What must happen first?
  3. A programmer says: "Binary search is always better than linear search. We should always use it." Identify the flaw in this reasoning and explain when linear search is the better choice.
  4. Compare selection sort and insertion sort on [1, 2, 3, 4, 5] (already sorted) versus [5, 4, 3, 2, 1] (reverse sorted). For each combination, describe qualitatively how much work is done. Which algorithm benefits more from the already-sorted input?
  5. Fill in the missing values: linear search for n=1,000 and n=1,000,000; binary search for n=1,000 and n=1,000,000; selection sort for n=1,000 and n=1,000,000.
Part DModerate and Mixed Questions
  1. A hospital database stores 500,000 patient records sorted by patient ID. A nurse looks up a patient by ID. Which search algorithm would you recommend and why? In the worst case, how many records does it need to examine?
  2. A music playlist stores 80 songs added in random order. Should the app use linear or binary search to find a specific song by title? If songs were sorted alphabetically first, would your answer change?
  3. A programmer says that selection sort "always does the same amount of work." In what sense is this true? In what sense is it a limitation?
  4. Consider two algorithms: Algorithm X always makes 90 comparisons for 10 items. Algorithm Y makes between 10 and 90 comparisons. Which is better? Is there a definitive answer? What additional information would help you decide?
  5. A student sorts 1,000 names using selection sort in 2 seconds. Sorting 10,000 names takes 200 seconds, not 20. Explain why. What Big-O category explains this? What would you expect for 100,000 names?

Debugging and Error Analysis

Error 1 — Binary Search Always Returns -1
def binary_search(items, target): low = 0 high = len(items) - 1 while low < high: # ← examine this condition mid = (low + high) // 2 if items[mid] == target: return mid elif target > items[mid]: low = mid + 1 else: high = mid - 1 return -1

Identify the bug. What happens when low and high point to the same index? What should the condition be?

Error 2 — Selection Sort Incorrect Results
def selection_sort(items): n = len(items) for i in range(n): # ← examine this range min_index = i for j in range(i + 1, n): if items[j] < items[min_index]: min_index = j items[i], items[min_index] = items[min_index], items[i] return items

The code runs without crashing but sometimes produces incorrect results. When i reaches the last position, what does the inner loop search? What should the outer range be?

Error 3 — Broken Insertion Sort Pseudocode
ALGORITHM BrokenInsertionSort(list): FOR i FROM 1 TO length(list) - 1: key ← list[i] j ← i - 1 WHILE j >= 0 AND list[j] > key: list[j] ← list[j - 1] # ← examine this line j ← j - 1 list[j + 1] ← key

What should list[j] be set to during the shifting step? Write the corrected line.

Error 4 — Wrong Algorithm for Unsorted Data
Applying binary search to [10, 50, 20, 40, 30] to find the value 40. The search returns -1 (not found).

The student is confused because 40 is clearly present. Explain exactly what went wrong. What precondition was violated? What should the student have done first?

ApplicationsDesign and Real-World Questions
  1. Library Strategy. A librarian needs to find a specific book in a collection of 50,000 books arranged alphabetically by author's last name. Write the search strategy as numbered steps. Which algorithm does your strategy resemble?
  2. Contact App. You are building a contact list app for a phone storing up to 500 contacts. Would you sort contacts alphabetically? Which search algorithm would you use for "find by name"? Would your approach change if contacts could also be searched by phone number?
  3. Daily Rankings. A class has 20 student test scores updated daily as new scores arrive. Students want to see their ranking whenever they ask. Would you sort the full list from scratch each day? Which sorting algorithm might be useful for maintaining a nearly-sorted list with small daily additions?
  4. Web Search. A website search engine must search through 10 billion web pages every time a user types a query. Explain why linear search through all pages is not feasible. What must be true about how pages are organized to make fast search possible?
  5. Spell Checker. A word processor checks whether every typed word exists in a dictionary of 200,000 words, sorted alphabetically. What algorithm would be used? How many comparisons does it need in the worst case? Why does this make spell-checking fast enough to keep up with a typist?
Mixed ReviewConnecting Earlier Chapters
  1. From Chapter 4. Write the number 12 in binary. If binary search works on a sorted list of 4,096 items, what is the maximum number of comparisons it needs? (Hint: 2¹² = 4,096.)
  2. From Chapter 3. Describe how binary search applies the principle of decomposition to the problem of finding an item in a sorted list.
  3. From Chapter 8. The binary search algorithm uses a while loop. Explain what condition controls the while loop and what happens when the condition becomes false.
  4. From Chapter 10. Describe a test case you would use to verify that a linear search implementation works correctly. Include at least one case where the target is present and one where it is absent.
  5. From Chapter 11. Binary search requires a sorted list or array. Explain why binary search would not work directly on a stack or queue without first converting to a sorted list.

Chapter 12 Checkpoint

Chapter 12 Checkpoint
Complete without assistance — covers all key skills and concepts from Chapter 12
Section 1 — Vocabulary and Concepts
  1. Define linear search and binary search. What is the key difference in how they work?
  2. What precondition does binary search require? What happens if that precondition is violated?
  3. Explain the difference between best-case and worst-case analysis. Why is worst-case analysis often more useful?
  4. In your own words, explain what O(n²) means and give an example of an algorithm in this chapter that fits this category.
Section 2 — Algorithm Tracing
  1. Trace linear search for target 44 in [92, 17, 44, 63, 5, 38]. How many comparisons?
  2. Trace binary search for target 77 in [3, 14, 27, 38, 51, 66, 77, 89, 95]. Show all steps with low, high, mid.
  3. Trace selection sort on [35, 8, 22, 4, 17]. Show the list after every pass.
  4. Trace insertion sort on [3, 7, 1, 5, 2]. Show the list after each insertion step.
Section 3 — Efficiency Analysis
  1. A list has 64 items and is sorted. What is the maximum number of comparisons binary search needs?
  2. Why does sorting once and searching many times often make a system more efficient overall?
  3. Place each algorithm in the correct Big-O category: (a) linear search, (b) binary search, (c) selection sort, (d) array index lookup.
Section 4 — Error Analysis
  1. A student runs binary search on an unsorted list and gets -1 (not found), even though the target is in the list. What went wrong and how would you fix it?
  2. A binary search while loop uses while low < high instead of while low <= high. Describe a case where this causes the algorithm to miss the target.
Section 5 — Application
  1. A school directory stores 3,000 student records sorted by last name. A secretary looks up a student by name many times each day. Which search algorithm should be used and why? Approximately how many comparisons are needed in the worst case?
  2. A programmer is sorting a list of 10 items that is nearly sorted already — only 2 items are out of place. Which sorting algorithm from this chapter would you recommend and why?
Looking Ahead
Chapter 13: Abstraction, Models, and Simulation

Chapter 13 introduces abstraction, models, and simulation — one of the most powerful ideas in computer science and in science generally. You have already encountered abstraction in this chapter: pseudocode abstracts away specific programming language details; Big-O notation abstracts away constant factors to focus on growth rate; a "sorted list" abstracts away what the items are and focuses only on their relative order.

Chapter 13 makes this concept explicit. Students will learn how computer scientists build simplified models of complex systems, what assumptions those models rely on, and how simulations allow us to study systems that would be too expensive, too dangerous, or too slow to study directly. Abstraction and modeling appear in every area of computing — databases model organizations, networks model communication, machine learning models data patterns, operating systems model physical hardware.

MGU Library Connection
  • Appendix F: Data Structures and Algorithms Reference — includes search and sort overviews and Big-O summary
  • Chapter 11: Data Structures at an Introductory Level — prerequisite for this chapter
  • Chapter 13: Abstraction, Models, and Simulation — follows directly from efficiency concepts here
  • Data Structures and Algorithms (later course) — covers mergesort, quicksort, heapsort, hash tables, trees
  • MGU Glossary entries: binary search, Big-O notation, linear search, selection sort, insertion sort, running time