Searching and Basic Sorting

16. Searching and Basic Sorting#

A service desk looks up one ticket by its ID. A payroll report lists employees in name order. An inventory system answers both kinds of question all day, but they are different tasks with different costs. This chapter develops the two most basic algorithms behind them, searching and sorting, and shows how to state what an answer must contain before counting the work needed to produce it. Chapter 13 introduced comparison, equality, and operation counts, and Chapter 14 introduced array and linked storage. Here those ideas are applied to complete, runnable implementations you can trace by hand.

  • Search contract: The promised result of a search, such as the first match, any match, all matches, or a missing report. A faster solution to a weaker contract is not a solution to the original task.

  • Linear and binary search: A first-match scan works on any array. Binary search halves a sorted candidate region on every step, but only when the data was sorted under the same ordering it uses.

  • Insertion sort: A small sorting algorithm that grows a sorted prefix one item at a time, preserves every occurrence, and keeps equal keys in arrival order.

  • Order and preservation checks: A sorted-looking result is not proof of correctness. Tests must confirm both the ordering and that no record was lost or duplicated.

  • Workload reasoning: One scan, a sorted snapshot searched many times, and a record set that changes after every query have different preparation, query, and update costs.

Section 16.1 states search contracts, traces first-match linear search and any-match binary search through successful, missing, and duplicate cases, and reads the result contracts of the library methods. Section 16.2 implements insertion sort with a comparer, counts its work on sorted and reverse inputs, verifies order and preservation, and then combines searching, sorting, and copying into a safe reporting workload where arrival order must survive. Chapter 7 introduced linear search, library sorting, binary search, and insertion sort on integer arrays; this chapter states their contracts and costs and adds comparers, stability, and snapshots. The supporting reading Merge Sort adds a recursive sort whose work grows with n log n, for large reporting workloads; it depends on Chapter 5’s Recursive Methods reading. Duplicate-boundary searches and quicksort wait for Part VI; the lessons here are the foundation that trees, heaps, and hash collections build on in Part V.

Chapter Video

Introduction to Binary Search (Data Structures & Algorithms #10) (14:22) by CS Dojo.

Hosted on YouTube; property of its original creator, embedded here for educational reference only.

Focus on the sorted-input requirement and the shrinking candidate interval. The sections use C# and add sorting, result policies, and reporting workloads.

Learning Objectives

By the end of this chapter, you will be able to:

  1. State the result contract of a search as first match, any match, all matches, or missing, and explain why a faster implementation of a weaker contract does not solve the original task.

  2. Trace first-match linear search and any-match binary search on small arrays, including empty input, a missing target, and duplicate values, and count the comparisons each one makes.

  3. Maintain the half-open interval [low, high) in binary search so that every iteration strictly shrinks the candidate region, and explain why the data must be sorted under the same comparer the search uses.

  4. Interpret the -1 sentinel returned by Array.IndexOf and the negative encoded insertion position returned by Array.BinarySearch before using either result as an index.

  5. Implement insertion sort with an IComparer, maintaining a sorted prefix that preserves every occurrence and keeps equal keys in their arrival order.

  6. Count insertion-sort comparisons for sorted, reverse-sorted, all-equal, and duplicate inputs, and state its linear best case and quadratic worst case.

  7. Verify a sort with both an order check and a preservation check, sort a clone when arrival order must be kept, and compare the preparation plus query cost of repeated scans against a sorted snapshot for a stated workload.

Chapter Flow

Assignments contains the preview, connected lab, and homework.

Recommended CS2 route: include Merge Sort after reviewing Recursive Methods. Trace a merge, implement the divide/sort/merge steps, and check order, preservation, and stability. The lighter applied route may omit this supporting reading; the standard assignments retain their existing scope.

Glossary

#

Term

Explanation

1

Search contract

The promised kind of result: first match, any match, all matches, or a missing report.

2

First-match search

A search that returns the earliest position whose value equals the target.

3

Any-match search

A search that may return the position of any equal value, not necessarily the first.

4

Linear search

Visit positions in order and stop at the first equal value; works on unsorted data.

5

Binary search

Repeatedly discard half of a sorted, random-access sequence until the target is found or the region is empty.

6

Sorted precondition

The requirement that binary search input be sorted under the same comparer the search uses.

7

Half-open interval

A candidate region [low, high) that includes low and excludes high; empty when low equals high.

8

Candidate region

The positions that could still hold the answer; it must shrink on every unsuccessful comparison.

9

Safe midpoint

The expression low + (high - low) / 2, which avoids overflow when adding two large indexes.

10

Sentinel

A special return value, such as -1, that signals a missing result instead of a valid index.

11

Encoded insertion position

The negative result of Array.BinarySearch, decoded with ~result to the index where the value would keep order.

12

Equality comparer

An object that decides whether two values match, such as ordinal or case-insensitive string equality.

13

Ordering comparer

An object whose Compare method returns a negative, zero, or positive sign meaning before, tied, or after.

14

Comparison sign

The only part of a comparer result a caller should test; the magnitude is not meaningful.

15

Insertion sort

A sort that keeps a sorted prefix and inserts each next item into its correct place within that prefix.

16

Sorted prefix

The leading positions that are already in order and hold the same occurrences as the original prefix.

17

Saved item

The next value, copied aside before larger prefix values shift right so the shifts cannot overwrite it.

18

Shift

Moving a prefix value one position to the right to open a gap for the saved item.

19

Stable sort

A sort that keeps equal keys in their original relative order, achieved here by shifting only strictly greater values.

20

Preservation

The obligation that sorted output contain exactly the input occurrences, with the same length and counts.

21

Best case

The input shape needing the least work; for insertion sort, already sorted data with n - 1 comparisons.

22

Worst case

The input shape needing the most work; for insertion sort, distinct reverse-sorted data with n(n - 1)/2 comparisons.

23

In-place sort

A sort that rearranges the array it was given using constant auxiliary element storage.

24

Snapshot

An independently ordered copy prepared for a report so the original arrival order stays unchanged.

25

Shallow copy

A clone that copies element values or references but not every object those references reach.

26

Boundary matrix

A small set of test inputs: empty, singleton, missing before and after the range, duplicates, all equal, sorted, reverse.

27

Workload

The mix of queries, updates, and required reports an algorithm choice must serve.

28

Preparation cost

The work done once before queries can run, such as sorting a snapshot.

29

Query cost

The work done for each individual search after any preparation.

30

Update cost

The work needed to keep a prepared structure valid after a record changes or arrives.

31

Run

A portion of an array that is already sorted, such as one branch office’s daily amounts.

32

Merge

Combining two sorted runs into one sorted array by repeatedly copying the smaller front element.

33

Merge sort

A recursive sort that splits an array in half, sorts each half, and merges the results in about n log n work.

34

Divide and conquer

Solving a problem by splitting it into smaller copies of itself and combining their answers.

35

Result coordinate

The sequence and position system to which a returned search index belongs.

Lecture Slides

Chapter 16 Slides