Sorting and Searching

Learn how programs find and order data efficiently. Write linear and binary search and adapt binary search to boundaries, ranges and thresholds. Implement selection sort, insertion sort, merge sort and quicksort, trace them on real data and analyze their costs with recurrences. See why comparison sorts need about n log n comparisons, and sort integer keys in linear time with counting sort and radix sort. Explain stability, compare the methods by time, memory and input order, and choose the right one for a task. Examples are in Python.

IntermediateLesson 4 of 10 in Data Structures and Algorithms Course

What you will learn

  1. Search a sequence for a target value, choose between linear and binary search, and adapt binary search to find positions, boundaries and thresholds.
    • Search any sequence with linear search
      Define the searching problem, write and trace linear search, and state its cost and when it is the right choice.
    • Halve the search range with binary search
      Write, trace and analyze binary search on a sorted array, and avoid the off-by-one errors that break it.
    • Adapt binary search to boundaries and thresholds
      Use binary search to find first and last occurrences, insertion points and ranges, with Python's bisect module, and to find the first value that satisfies a yes-or-no condition.
  2. Describe the sorting problem and the measures used to compare sorts, implement selection sort and insertion sort, and explain stability and why it matters.
    • Describe the sorting problem and how sorts are compared
      Define sorting, keys and comparison sorts, and judge an algorithm by its comparisons, data moves, extra memory, adaptivity and correctness.
    • Sort by repeated selection
      Implement and trace selection sort, count its comparisons and swaps, and explain why it is not stable.
    • Sort by repeated insertion
      Implement and trace insertion sort, relate its cost to the number of inversions, and explain why it excels on small and nearly sorted inputs.
    • Explain stability and use it to sort by several keys
      Define a stable sort, identify which algorithms are stable, and use stability to sort records by more than one key.
  3. Implement merge sort and quicksort, analyze them with recurrences, and explain how pivot choice, duplicates and memory affect quicksort.
    • Sort by splitting and merging with merge sort
      Write the merge step and merge sort, trace them on real data, and derive their n log n cost and memory use.
    • Partition around a pivot with quicksort
      Implement quicksort with Lomuto partitioning, trace a partition by hand, and recognize Hoare partitioning and quicksort's instability.
    • Analyze quicksort and choose pivots well
      Derive quicksort's best, worst and expected costs, and use random pivots, three-way partitioning and smaller-side recursion to make it fast and safe.
  4. Prove that comparison sorts need about n log n comparisons, and use counting sort and radix sort to sort integer keys faster when their range allows it.
    • Prove the n log n lower bound for comparison sorting
      Model a comparison sort as a decision tree, derive the bound log₂(n!), and state what the bound does and does not rule out.
    • Sort small-range integer keys with counting sort
      Implement stable counting sort with counts and starting positions, trace it, and state when its linear cost pays off.
    • Sort integers digit by digit with radix sort
      Run LSD radix sort with a stable digit sort, explain why stability makes it correct, and choose a base to balance passes and memory.
  5. Weigh the costs and properties of every method in this unit and choose a suitable sorting and searching approach for a concrete task.
    • Compare the algorithms by cost and properties
      Summarize the time, memory, stability and adaptivity of each search and sort, and explain why constant factors and input order matter as well as growth rates.
    • Choose a sorting and searching approach for a task
      Match the method to the data and the requirements, decide when sorting before searching pays off, and justify the choice with costs.

Sorting and Searching study guide

5 chapters

1

Find items with linear and binary search

A search returns a matching position or reports absence. The right method depends on how the data is organized and what result is needed. Start with a scan that works on any sequence, then use sorted order to shrink a candidate range. Finally, turn that same range idea into insertion points, counts, nearest values, and the first input that satisfies a condition. Bounds and invariants make each discarded region safe.

1.1 Search one item at a time

A search asks for the position of a target, or a clear indication that it is absent. Linear search checks items in their existing order. It works even when the sequence has no useful ordering.

Write the loop and its result
def linear_search(a, target):
    for i in range(len(a)):
        if a[i] == target:
            return i
    return -1

The loop stops at the first match, so duplicates return the first matching index. The failure return comes after the loop: only then have all positions been ruled out. An else: return -1 attached to the equality test would give up at the first mismatch.

In [42, 17, 8, 99, 23], a search for 99 checks 42, 17, 8, then 99. Four comparisons find index 3. A search for 5 checks all five items and returns -1. An empty list also returns -1, with no comparisons.

Check that result before indexing. In Python, a[-1] means the last item; it does not mean "no item." For example:

i = linear_search(a, target)
if i != -1:
    print(a[i])
Count the work

For a nonempty list of length n, the best case takes one comparison, when the target is first. The worst case takes n comparisons, when it is last or absent. If a successful target is equally likely to occupy any position, the average is

(1+2+⋯+n)/n=(n+1)/2.

Thus worst-case and uniformly distributed successful-search time are Θ(n). The index and target use O(1) extra memory. The average formula needs its probability model: frequently requested values near the front can make real searches much shorter.

With no ordering information, an absent-target search must inspect every position. Any unchecked item could still be the target. A linked list also suits a sequential scan: following its next pointers is natural, whereas jumping to an arbitrary middle position is expensive.

Change what counts as a match

The same loop can return the first order whose mass exceeds 100 kg. To collect all matches, append each matching index and continue to the end; this also needs space for the returned indexes. On sorted ascending data, a scan may stop when the current value exceeds the target, because later values cannot match. That early stop improves some searches but leaves a linear worst case.

Python list membership, x in a, scans for a match. a.index(x) returns its index but raises ValueError if absent; catch that error when absence is normal. a.count(x) must inspect the entire list to count every occurrence. Checking membership and then calling index can scan the same prefix twice.

If a loop processes m targets and each uses membership on an n-item list, the total is O(nm), reaching Θ(nm) when searches reach the end. If each matches the first item, it is only Θ(m). For repeated membership alone, a hash set can offer expected constant-time lookups; for one or a few searches of a small unsorted sequence, the direct scan is often the useful starting point.

Key Takeaways

  • Linear search works on unsorted sequences and stops at the first match.
  • Return failure after the loop, and check a failure sentinel before indexing.
  • Worst-case time is Θ(n) and extra memory is O(1).
  • Repeated list membership tests can create a quadratic workload.

1.2 Keep and shrink a candidate range

Binary search uses sorted order to eliminate many positions after each probe. The array must be sorted in the same order as the search comparisons, and indexing must take constant time for logarithmic running time.

Use inclusive bounds consistently

Keep both endpoints of the candidate range included. The invariant is: "If the target occurs, an occurrence remains between lo and hi."

def binary_search(a, target):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == target:
            return mid
        if a[mid] < target:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

When a[mid] < target, every value at or left of mid is too small. The next range begins at mid + 1. When it is larger, the range ends at mid - 1. Both updates discard the tested position and guarantee progress. An empty range has lo > hi.

Trace the bounds

Use [3, 8, 15, 21, 34, 42, 57, 66, 79, 91] and target 57:

  1. Bounds 0 through 9 give mid = 4. Value 34 is too small, so lo = 5.
  2. Bounds 5 through 9 give mid = 7. Value 66 is too large, so hi = 6.
  3. Bounds 5 through 6 give mid = 5. Value 42 is too small, so lo = 6.
  4. Bounds 6 through 6 give mid = 6. Value 57 matches.

For target 20, the probed values are 34, 8, 15, and 21. The last update gives lo = 3, hi = 2: absence is established. The final lo is the insertion position between 15 and 21.

Separate probes from implementation work

For n≥1, the maximum number of middle-element probes is ⌊log⁡2n⌋+1: 4 for 10 items, 10 for 1000, 20 for one million, and 30 for one billion. A probe here means examining one middle element; Python may evaluate both == and < during that probe. Worst-case time is Θ(log⁡n) and the best case is Θ(1). An empty array takes zero probes.

The loop needs O(1) extra memory. A recursive implementation passes the original array plus bounds, using O(log⁡n) stack space. Recursing on a[mid + 1:] copies a slice. Along a long search path the copies total about half the input plus a quarter plus an eighth, giving Θ(n) worst-case copying time. Local slice indexes also lose their direct connection to the original positions.

Catch the small boundary bugs

With inclusive hi, while lo < hi skips a remaining one-item range. Setting lo = mid can repeat the same two-item range forever. Test lengths 0, 1, and 2, including targets below and above all items. A half-open implementation can be correct too, but its bounds and updates must follow that convention throughout.

Python integers do not overflow. With nonnegative Java int bounds, use lo + (hi - lo) / 2 to avoid overflowing lo + hi. On linked lists, reaching successive middle nodes can require linear traversal overall, so logarithmically many comparisons do not give logarithmic time. Inserting into a sorted array also remains linear in the worst case because later items must shift.

Key Takeaways

  • Binary search needs sorted data; logarithmic time also needs constant-time indexing.
  • The candidate-range invariant justifies discarding each half.
  • Inclusive bounds require lo <= hi and updates that exclude mid.
  • For nonempty input, at most ⌊log⁡2n⌋+1 middle probes are needed.
  • Pass bounds in recursive search; slicing adds copying and changes local indexes.

1.3 Find boundaries, counts, and thresholds

Finding any match is different from finding the first match. With duplicate keys, a boundary search continues after equality so it can locate the edge of an equal-key block.

Find the first value at least as large

The leftmost insertion point is the first index with a[i] >= x, or the length of the array if no such item exists. Use a half-open candidate range:

def leftmost(a, x):
    lo, hi = 0, len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if a[mid] < x:
            lo = mid + 1
        else:
            hi = mid
    return lo

Everything before lo is smaller than x; everything from hi onward is at least x. Equality moves hi, retaining the possibility of an earlier equal item. At termination, both bounds identify the boundary. To find the first value strictly greater than x, change < to <=.

Python supplies bisect_left and bisect_right. For a = [1, 2, 2, 2, 5, 7], the two positions for 2 are 1 and 4. The last occurrence is index 3, and the count is 3. For 4, both searches return 4, even though 4 is absent. Check membership separately:

from bisect import bisect_left, bisect_right
i = bisect_left(a, x)
found = i < len(a) and a[i] == x

The length check comes first because an insertion point can lie just beyond the array. C++ calls these searches lower_bound and upper_bound.

Use two boundaries or two neighbors

A closed interval includes both endpoints. Count its items with

count = bisect_right(a, high) - bisect_left(a, low)

On [3, 8, 15, 21, 34, 42, 57, 66, 79, 91], the interval from 20 through 60 starts at index 3 and ends just before index 7. It contains four items. Finding the count takes O(log⁡n) time without scanning those items.

For the nearest value to x, find i = bisect_left(a, x). Only a[i - 1] and a[i] can be closest: earlier values are no closer than the predecessor, and later values no closer than the successor. Check that each neighbor exists. For x = 50, the candidates 42 and 57 have distances 8 and 7, so choose 57. If distances tie, either is nearest unless a tie rule is specified.

Search a condition instead of a stored array

A monotone condition is false up to a boundary and true from there onward. On nonnegative integers, x * x >= 200 has this shape. Binary search locates its first true value, 15: 14 squared is 196, while 15 squared is 225. Searching the inclusive domain 0 through 200 with a first-true search takes eight tests. The same idea finds the first faulty software version when every version after the fault is also faulty. Among versions 1 through 1000, at most ten tests suffice. A condition that turns true, then false again cannot justify discarding one whole side.

Search and insert records

With bisect_left(records, year, key=lambda r: r[0]), the key function is applied to stored records, while the supplied search value is already a year. In contrast, insort applies the key function to the new record for its search and then inserts that whole record. Its default position is after existing equal keys. Searching takes O(log⁡n) comparisons, but shifting the list for insertion still takes O(n) time.

Key Takeaways

  • Left and right insertion points locate the whole block of equal values.
  • Check an insertion point against the array length and target before claiming a match.
  • Closed-range counts use the right boundary of the high value minus the left boundary of the low value.
  • The nearest value lies beside the insertion point, with missing neighbors handled explicitly.
  • First-true search requires a condition that stays true after its threshold.
  • bisect searches with a key value; insort inserts a complete item.
2

Sort with simple methods and judge any sorting algorithm

Sorting has two obligations: put keys in order and preserve every input item. Simple sorting loops make those obligations visible. Selection sort fixes the next position by finding a minimum; insertion sort expands a sorted prefix by moving the next item into place. Their costs expose the difference between comparisons and writes. Equal-key records add a further requirement: stability, which makes multi-key ordering possible.

2.1 Define what a correct sort preserves

Sorting rearranges items into nondecreasing order of a chosen key. Equal keys are allowed. A correct result must also preserve every input item, including its number of occurrences.

Move whole items by their keys

A record may hold a name, score, and arrival time. If score is the key, the entire record moves when its position changes. Sorting scores alone and leaving names in place would attach results to the wrong people.

records = [("Mina", 73), ("Omar", 61), ("Pia", 73)]
ordered = sorted(records, key=lambda r: r[1])

ordered is a new list. The original records remains available. records.sort(key=lambda r: r[1]) modifies that list and returns None; assigning its return value back to records loses the reference to the list. Keys need a consistent ordering so comparisons can determine which item belongs first.

Sortedness requires key(a[i - 1]) <= key(a[i]) for every adjacent pair. The second requirement is that the output is a permutation of the input: the same items with the same multiplicities. A result like [1, 1, 3] is sorted but cannot be a correct sort of [1, 2, 3].

Measure the costs separately

A comparison sort discovers order by comparing pairs of keys. Selection, insertion, merge, and quicksort do this. Counting and radix sort use key values or digits directly as counter indexes, so they use a different model.

A useful analysis counts key comparisons, moves or writes, and extra memory as well as elapsed time. A swap typically writes more than one location. Fewer comparisons need not mean fewer writes. State whether a bound describes the best, worst, or average input; an average also needs a distribution of inputs.

Three properties answer different questions:

  • In place: only constant extra storage beyond the input under the strict definition. Quicksort rearranges its array directly, but its stack must still be reported.
  • Adaptive: able to exploit existing order, as insertion sort does.
  • Stable: preserves the input order of equal-key records.

A sort can have any one of these properties without having the others. Stable ordering is about ties, not a promise about running time.

Count disorder and argue correctness

An inversion is a pair of positions i < j whose values satisfy a[i] > a[j]. In [3, 1, 2], the pairs (3, 1) and (3, 2) are inversions. A sorted list has zero; reversing n distinct values gives n(n−1)/2. Swapping adjacent inverted items removes exactly one inversion. This connects a measure of disorder with insertion sort's work.

A loop invariant states what is already correct before each pass. Prove it holds initially, survives a pass, and implies the result when the loop ends. In selection sort, the prefix contains the smallest items in final order. Merely observing that the prefix is sorted is weaker: it also has to contain the right items.

Test empty and one-item inputs, duplicates, all-equal keys, sorted input, and reversed input. Compare numeric output with sorted(original) to check both order and multiplicities. For stability tests, use labeled records with equal keys so their relative order is visible.

Key Takeaways

  • A correct sort produces nondecreasing keys and preserves all items with their multiplicities.
  • The key determines order; the complete record moves.
  • Comparisons, writes, memory, and cost cases describe different parts of performance.
  • In-place storage, adaptivity, and stability are separate properties.
  • Inversions measure out-of-order pairs.
  • Invariants explain correctness; tests should check preservation as well as order.

2.2 Select the next smallest item

Selection sort grows a finished prefix by searching the remaining suffix for its minimum. Each pass chooses the item for one final position.

Scan first, swap once
def selection_sort(a):
    for i in range(len(a) - 1):
        m = i
        for j in range(i + 1, len(a)):
            if a[j] < a[m]:
                m = j
        if m != i:
            a[i], a[m] = a[m], a[i]

m stores an index, not the minimum value. It begins at i, the first unsorted position. The inner loop updates that index whenever it sees a smaller item. Only after scanning the suffix does the algorithm swap. The guard avoids swapping a position with itself.

Before pass i, positions before i hold the i smallest items in sorted order. The scan finds the smallest remaining item, so the swap extends that prefix by one. Once all but the last position are fixed, the last item must also be correct. Empty and one-item lists require no passes.

Follow a complete example

Start with [29, 10, 14, 37, 13]:

  1. Scan all five items. The minimum is 10 at index 1. Swap with index 0: [10, 29, 14, 37, 13].
  2. Scan the suffix beginning at index 1. Its minimum is 13. Swap it with 29: [10, 13, 14, 37, 29].
  3. The next suffix has minimum 14, already at index 2. Leave it there.
  4. The last two values are 37 and 29. Swap them to obtain [10, 13, 14, 29, 37].

The scans used 4, 3, 2, and 1 comparisons, totaling 10. There were three actual swaps. The third pass still made comparisons even though it needed no swap.

Explain the tradeoff

For n items, the exact comparison count is

(n−1)+(n−2)+⋯+1=n(n−1)/2.

For 1000 items, that is 499,500 comparisons. Already sorted input has the same count: the algorithm still has to establish each suffix minimum. Its best, average, and worst running times are Θ(n2). It is not adaptive.

There are at most n−1 actual swaps and only O(1) extra storage. On a small input where writes are much more expensive than reads, this low swap count can matter. Swapping immediately whenever a new minimum is encountered sacrifices that advantage, even if the resulting variant still sorts correctly.

A recursive version places the largest item at the end, then sorts the remaining prefix. It obeys T(n)=T(n−1)+Θ(n), so recursion changes the presentation without improving the quadratic cost.

Watch equal-key records

Sort [(5, "a"), (5, "b"), (3, "c")] by the numeric key. The first swap puts (3, "c") first and moves (5, "a") past (5, "b"). The two 5-key records reverse order, so ordinary selection sort is unstable. Keeping the first minimum during the scan does not prevent that long-distance crossing.

A stable variant removes the minimum and shifts intervening records right before inserting it. It preserves ties but can need quadratic moves. This is a different tradeoff from the few-swaps version. Keep the search inside the unsorted suffix; searching from index 0 again can disturb positions already fixed.

Key Takeaways

  • Each pass finds the minimum of the unsorted suffix and fixes one position.
  • Selection sort always makes n(n−1)/2 key comparisons.
  • The guarded implementation uses at most n−1 actual swaps and constant extra space.
  • Long-distance swaps make the usual algorithm unstable.

2.3 Insert the next item into a sorted prefix

Insertion sort takes the next item in input order and fits it into a sorted prefix. It saves that item, shifts larger items to make a gap, then fills the gap.

Preserve the item while making room
def insertion_sort(a):
    for i in range(1, len(a)):
        x = a[i]
        j = i - 1
        while j >= 0 and a[j] > x:
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = x

Before iteration i, a[:i] is sorted and holds the items originally in that prefix. Saving x matters because the first shift overwrites its old slot. The bounds check comes before a[j] > x, so Python stops before accessing a position left of the prefix.

Shifting stops at a value no larger than x, or at the left edge. Position j + 1 is then exactly the gap where x belongs. Inserting it preserves order and every item, extending the invariant by one position.

Trace shifts separately from comparisons

For [7, 3, 5, 1, 9, 2]:

  1. Insert 3 by shifting 7: [3, 7, 5, 1, 9, 2].
  2. Insert 5 by shifting 7: [3, 5, 7, 1, 9, 2].
  3. Insert 1 by shifting 7, 5, and 3: [1, 3, 5, 7, 9, 2].
  4. Insert 9 with no shift.
  5. Insert 2 by shifting 9, 7, 5, and 3: [1, 2, 3, 5, 7, 9].

There are nine shifts. Counting only comparisons between values gives twelve: the five iterations use 1, 2, 3, 1, and 5. A comparison that stops the loop may add work without causing a shift; reaching j = -1 stops through the bounds test instead.

Connect work with disorder

Each shift moves a larger preceding value past x, removing one inversion. The number of shifts therefore equals the input's inversion count I. Including the outer loop, running time is Θ(n+I).

A sorted nonempty list has zero shifts and n−1 value comparisons: Θ(n) time. A reversed list of distinct keys has n(n−1)/2 shifts and value comparisons: Θ(n2) time. Randomly ordered distinct keys also give quadratic average time, with roughly n2/4 comparisons.

When each item's displacement from its final position is at most a small k, insertion sort costs O(n(k+1)). Including the 1 keeps the bound meaningful even when k=0. This adaptivity makes it useful for nearly sorted data. It also works online: insert each newly arriving item into the prefix already maintained.

Keep ties and limits correct

The strict test a[j] > x leaves earlier equal-key records before x, making insertion sort stable. Changing it to >= shifts those equal records and can reverse them. The algorithm needs O(1) extra space.

Omitting j >= 0 is dangerous in Python because negative indexes wrap around to the end. The loop can overwrite values before it eventually raises IndexError; on [2, 1], the corrupted list becomes [2, 2]. Binary search can reduce the comparisons used to find a gap, but cannot remove the quadratic worst-case shifts. Small pieces inside hybrid sorts often use insertion sort because its simple loop has little overhead.

Key Takeaways

  • Save the next item, shift strictly larger prefix items, then fill the gap.
  • The sorted-prefix invariant explains why each insertion is correct.
  • Shifts equal inversions, giving Θ(n+I) time.
  • Sorted input takes linear time; reversed distinct input takes quadratic time.
  • The strict comparison preserves stability, and the bounds test prevents negative-index errors.

2.4 Keep equal-key records in order

A stable sort preserves the relative input order of records with equal keys. It matters when a record has information beyond the key, such as an arrival time or a name.

See what a tie preserves

Consider [("Ana", 88), ("Ben", 92), ("Cai", 88), ("Dev", 75), ("Eli", 92)]. Sorting by score in descending order with Python gives Ben, Eli, Ana, Cai, Dev. Ben remains before Eli, and Ana remains before Cai. Python's reverse=True preserves stability too; it does not reverse the equal-score groups.

Stability leaves the order of ties unchanged; it does not create an alphabetical order that was absent. If Cai appeared before Ana initially, a stable score-only sort would keep Cai first among those two. Equal plain integers have no visible identities, so reordering two copies of 88 makes no visible difference.

Build an order from several keys

Suppose scores should descend and equal scores should be alphabetical by name. Sort by the less important key first, then use a stable sort for the more important key:

by_name = sorted(records, key=lambda r: r[0])
result = sorted(by_name, key=lambda r: r[1], reverse=True)

The name pass establishes the tie order. The score pass groups scores and preserves name order inside each group. Reversing the pass order makes name the final primary key instead.

One tuple key expresses the same priority:

result = sorted(records, key=lambda r: (-r[1], r[0]))

Tuple comparison first uses negative score, so higher scores come first, then name when scores tie. The key's order, or the order of stable passes, determines which field is primary.

Find the implementation detail that protects ties

Insertion sort is stable when it shifts only strictly larger keys. Merge sort is stable when equal front keys are taken from the left half first. Counting sort is stable when equal-key records are placed in input order. LSD radix sort depends on stable digit passes so later passes retain the lower-digit ordering already built.

Usual selection sort and quicksort are unstable because their long-distance swaps can move a record across another with an equal key. An algorithm name alone is insufficient: changing merge's left-on-ties test from <= to < can break stability, just as changing insertion's > to >= can.

Preserve original positions explicitly

If a sorting method is unstable, extend each key with the record's original index. Sorting by (key, original_index) forces equal original keys into their input order, because their indexes differ. Storing those indexes alongside the items costs Θ(n) extra space and adds a tie-breaking comparison when keys match.

For everyday Python code, sorted and list.sort already guarantee stability. Java guarantees stable object sorting through Arrays.sort and Collections.sort. Its primitive-array sort uses a dual-pivot quicksort implementation; equal primitive values carry no distinct record identity. Stability describes tie order, not whether an algorithm avoids crashes or guarantees a worst-case time.

Key Takeaways

  • Stability preserves the input order of equal-key records.
  • For repeated stable passes, sort the secondary key first and the primary key last.
  • A tuple key lists fields in priority order.
  • Tie handling determines whether insertion, merge, and counting implementations stay stable.
  • Original indexes can supply an explicit tie breaker for an unstable sort.
  • Python guarantees stable sorting, including descending sorts.
3

Sort in n log n time with divide and conquer

Divide and conquer makes large sorts practical by breaking them into shrinking problems. Merge sort splits first and combines sorted results afterward. Quicksort partitions first and then orders the resulting regions. Follow the work in each phase, including the moment when a pivot becomes fixed or two fronts are compared. Recursion shape, tie handling, and memory use explain why the two algorithms offer different guarantees.

3.1 Split, sort, and merge

Merge sort divides an array into smaller problems, solves them, and combines their sorted results. Its base case is a list of length zero or one, which is already sorted.

Merge two sorted lists

Keep an index into each list. Compare their front items and move the smaller one to the output. When one list runs out, copy the other list's remaining items; they are already in order.

def merge(left, right):
    out = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i])
            i += 1
        else:
            out.append(right[j])
            j += 1
    out.extend(left[i:])
    out.extend(right[j:])
    return out

def merge_sort(a):
    if len(a) <= 1:
        return a[:]
    mid = len(a) // 2
    return merge(merge_sort(a[:mid]), merge_sort(a[mid:]))

For records, compare their keys while copying whole records. Taking the left item on equal keys preserves input order across the two halves. If each recursive result is stable, that tie rule makes the whole algorithm stable.

Merge [2, 5, 8] with [3, 4, 9, 10]. The winning fronts are 2, 3, 4, 5, and 8. After those five comparisons the left list is empty; append 9 and 10 without further comparisons. The result is [2, 3, 4, 5, 8, 9, 10]. For two nonempty lists of lengths p and q, at most p+q−1 comparisons are needed. Copying the whole output costs Θ(p+q) time even when comparisons finish early.

Follow the recursive structure

For [38, 27, 43, 3, 9, 82, 10], split into [38, 27, 43] and [3, 9, 82, 10]. Recursively sorting gives [27, 38, 43] and [3, 9, 10, 82]. Their final merge takes 3, 9, 10, 27, 38, and 43, then appends 82. Counting all merges throughout the recursion gives thirteen comparisons.

The halves need not have equal lengths. With an odd size, one has one extra item. What matters is that both recursive problems shrink. A split that repeatedly sends the entire input into one recursive call never reaches the base case.

Account for levels and memory

For equal halves, the time recurrence is

T(n)=2T(n/2)+Θ(n).

At each level, merging handles a total of n items. There are about log⁡2n levels, so plain merge sort takes Θ(nlog⁡n) time on sorted, reversed, and random inputs. For one million items, nlog⁡2n is about 20 million; a quadratic sort's roughly 500 billion comparisons are about 25,000 times as many.

Array merging needs Θ(n) extra storage, plus a logarithmic recursion stack. Python slices add copying at each level but keep this implementation's overall time at Θ(nlog⁡n). Peak live extra memory remains linear. On linked lists, merging can relink existing nodes instead of allocating an output array.

Bottom-up merge sort removes recursion: merge adjacent runs of length 1, then 2, then 4, doubling until one run remains. The time remains Θ(nlog⁡n). Always copy leftovers: forgetting them can produce sorted-looking output that has silently lost input items.

Key Takeaways

  • Merge sort recursively sorts smaller halves and merges their results.
  • Merge by comparing front items, then copy the remaining tail.
  • Taking from the left on ties preserves stability.
  • Linear work at each logarithmic level gives Θ(nlog⁡n) time.
  • Array merge sort needs linear extra memory; linked-list merging can relink nodes.
  • Bottom-up merging doubles run sizes without recursion.

3.2 Partition a range around a pivot

Quicksort organizes a range around a pivot, then recursively sorts its two sides. The partition does the combining work in advance, so no later merge is needed.

Maintain two regions while scanning

Lomuto partition uses the last value as pivot. During the loop, positions lo through i hold keys no larger than the pivot; positions i + 1 through j - 1 hold larger keys. Positions from j onward have not yet been classified.

def partition(a, lo, hi):
    pivot = a[hi]
    i = lo - 1
    for j in range(lo, hi):
        if a[j] <= pivot:
            i += 1
            a[i], a[j] = a[j], a[i]
    a[i + 1], a[hi] = a[hi], a[i + 1]
    return i + 1

def quicksort(a, lo, hi):
    if lo < hi:
        p = partition(a, lo, hi)
        quicksort(a, lo, p - 1)
        quicksort(a, p + 1, hi)

A small item expands the first region by one and swaps into its new slot. A large item stays in the second region. The final swap puts the pivot between them. The returned index is the pivot's final sorted position, even though neither side is sorted yet.

Trace a partition without sorting its sides

Start with [6, 3, 9, 1, 8, 2, 7, 5], pivot 5. Scanning 6 leaves the boundary unchanged. Moving 3 to the first region gives [3, 6, 9, 1, 8, 2, 7, 5]. Moving 1 next gives [3, 1, 9, 6, 8, 2, 7, 5]. Moving 2 gives [3, 1, 2, 6, 8, 9, 7, 5].

After seven comparisons, swap the pivot into index 3:

[3, 1, 2, 5, 8, 9, 7, 6]

The recursive calls handle indexes 0 through 2 and 4 through 7. Partitioning alone has established each side's relationship to 5; it has not ordered the values inside either side. If both recursive calls sort correctly, their results fit together with 5 to give the sorted whole.

Match recursion to the partition contract

Lomuto excludes the final pivot from both recursive calls. Including it again with quicksort(a, lo, p) can repeat the original range when the pivot lands at hi. The test lo < hi skips both one-item and empty ranges.

Hoare partitioning scans inward from both ends and swaps items on the wrong side until its indexes cross. It returns a split boundary, not a guarantee that one pivot item occupies its final position. Its recursive ranges are lo..p and p+1..hi. These bounds belong to Hoare's contract; mixing them with Lomuto's can prevent termination or leave items unsorted. Hoare usually makes fewer swaps and distributes equal keys better.

For a random or median-of-three pivot with the Lomuto code, first swap that chosen item into a[hi]. The loop and final swap assume it is there.

Partition needs O(1) extra storage; recursion adds a stack. Long swaps make ordinary quicksort unstable. For keys [(2, "a"), (2, "b"), (1, "c")], the final pivot swap can produce [(1, "c"), (2, "b"), (2, "a")], reversing the two 2-key records.

Key Takeaways

  • Lomuto maintains a region no larger than the pivot and a region larger than it.
  • The final swap places the Lomuto pivot in its final position.
  • Quicksort must still sort both sides after partitioning.
  • Lomuto and Hoare return different things and require different recursive bounds.
  • Partitioning rearranges the array directly, but quicksort also needs stack space.

3.3 Control quicksort time and stack depth

A partition scans its range once. For Lomuto on m items, that means m−1 pivot comparisons. The total cost depends on how much the recursive ranges shrink.

Compare the recursion shapes

When pivots split ranges near the middle,

T(n)=2T(n/2)+Θ(n)=Θ(nlog⁡n).

Each level handles at most linear total data, and there are logarithmically many levels. Even consistent 9-to-1 splits retain logarithmic depth; balance need not mean exact halves.

If every pivot is an extreme value, only one item is removed per level:

T(n)=T(n−1)+Θ(n)=Θ(n2).

The comparison count becomes n(n−1)/2, or 499,500 for 1000 items. Choosing the last item on already sorted distinct input produces this chain. Reversed distinct input is also a worst case for this rule.

Randomize the pivot, handle duplicates separately

For distinct keys, choosing each pivot uniformly at random gives expected Θ(nlog⁡n) time for every fixed input order. The expectation is over pivot choices, not over a promise that users supply shuffled data. A bad sequence remains possible.

The expected comparison count is 2(n+1)Hn−4n, where Hn=1+1/2+⋯+1/n. For large inputs it is about 1.39 nlog⁡2n, and for 1000 distinct items about 10,986 comparisons.

Median-of-three chooses the median of the first, middle, and last values. It improves sorted and reversed inputs at the cost of a few selection comparisons. It is a heuristic, not a worst-case guarantee: other arrangements can still force poor splits.

Duplicates need another idea. If all keys equal the pivot, Lomuto's <= test puts them all on one side. Changing the pivot randomly does nothing because every candidate has the same key. Three-way partitioning creates less-than, equal-to, and greater-than regions, then recurses only on the less and greater regions. All-equal input is finished in one linear pass. Combining three-way partitioning with random pivots gives expected O(nlog⁡n) time even with repeated keys.

Bound the stack independently of the work

The direct recursive implementation can nest linearly many calls. Python's usual default recursion limit is 1000, so a last-pivot quicksort on 5000 sorted items can reach RecursionError before finishing. Increasing a limit does not remove the quadratic work.

Instead, recurse only on the smaller side and process the larger side with a loop. Every nested call is at most half the current range, so the stack has O(log⁡n) depth even when partition quality is poor. The loop can still do quadratic total work: stack space and running time are separate bounds.

Quicksort often performs well on arrays because partitioning scans memory directly with little auxiliary storage. Practical implementations commonly use insertion sort for tiny ranges. Java's primitive-array sorting documents a dual-pivot quicksort implementation. For stable ordering or a guaranteed Θ(nlog⁡n) worst case, array merge sort offers those properties at the cost of an auxiliary array.

Key Takeaways

  • Proportional splits give logarithmic depth and Θ(nlog⁡n) time.
  • Repeated extreme pivots cause quadratic work.
  • Random pivots give expected bounds, not a deterministic worst-case guarantee.
  • Three-way partitioning removes equal keys from further recursion.
  • Recursing on the smaller side bounds stack depth without fixing bad partition work.
  • Median-of-three improves familiar inputs but can still have a quadratic worst case.
4

Know the limit of comparison sorting and sort integers in linear time

A limit on comparison sorting explains both the success of merge sort and the appeal of integer-key methods. Model comparisons as decisions that must distinguish all possible input orders. Then change the available information: small integer keys can index counters, and longer keys can be read one digit at a time. Counting and radix sort gain speed from that structure, with range size, digit count, and stability determining their usefulness.

4.1 Count the information comparisons must reveal

A comparison sort learns key order only through comparisons between pairs. A lower bound in this model applies to every such algorithm, including ones not yet invented.

Represent an algorithm as a decision tree

Use distinct keys so an order comparison has two possible outcomes. Each internal node is a question such as whether one key is smaller than another. Each branch represents an answer. A root-to-leaf path is one execution, and its length is the number of comparisons made on that input.

There are n! possible relative orders of n distinct keys. Correct sorting must distinguish all of them, because each requires its own rearrangement of the original positions. The tree therefore needs at least n! leaves. A binary tree of height h has at most 2h leaves, so

2h≥n!,h≥⌈log⁡2(n!)⌉.

This is a worst-case claim: some input must follow a path at least that long. It is not a claim that every execution must use the maximum number of comparisons.

For three items, there are six orders. Two comparison levels allow only four leaves, so at least three comparisons are needed in the worst case. Insertion sort reaches that bound on [3, 2, 1]. For four items, 24 orders require at least five levels. Merge sort uses at most five comparisons on four items, so its bound is exactly optimal at that size.

Turn the factorial bound into a growth rate

For even n, at least half the factors in n! are at least n/2. Thus

log⁡2(n!)≥(n/2)log⁡2(n/2)=Ω(nlog⁡n).

The same asymptotic conclusion holds for odd sizes by rounding the half-size terms. A more precise estimate is log⁡2(n!)≈nlog⁡2n−1.44n. The lower bounds are 7 comparisons for five items, 22 for ten, and 29 for twelve. For one million, the information requirement is about 18.5 million comparisons, close to nlog⁡2n≈19.9 million.

Merge sort's worst-case Θ(nlog⁡n) time matches this growth rate, so no comparison sort can improve the worst-case order below it. This does not promise identical constants or equal speed on a particular machine.

Keep the quantifiers and the model attached

The average depth across the leaves is also at least log⁡2(n!) when distinct-key input orders are equally likely. Randomization cannot eliminate that average information requirement. Randomized quicksort remains within a constant factor, with about 1.39nlog⁡2n expected comparisons for large distinct-key inputs.

Already sorted input can still take only n−1 comparisons with insertion sort. A fast special case is compatible with a lower bound on the worst case and on the uniform average. Likewise, counting and radix sort can be linear on suitable integer keys because they inspect key values or digits directly instead of relying only on pairwise comparisons.

Searching has a related information limit. For sorted-array membership using probes that compare a target with an element, some target needs ⌊log⁡2n⌋+1 probes for nonempty arrays. Binary search attains it. Count a probe consistently: a three-way comparison outcome is one middle-element test, even when source code uses separate equality and ordering operators.

Key Takeaways

  • A decision tree models comparisons as branches and completed rearrangements as leaves.
  • Distinct keys require at least n! leaves.
  • The worst-case comparison count is at least ⌈log⁡2(n!)⌉=Ω(nlog⁡n).
  • The bound concerns a model and cost case; it permits faster special inputs.
  • Counting and radix sort use information outside the comparison model.

4.2 Place integer-key records with counts

Counting sort uses an integer key as an index into a counter array. It is useful when the possible key range is small enough to store and scan.

Count, find starts, then place

For keys in 0..k-1, allocate k counters. A stable implementation first counts each key, computes the starting position of each key's block, then places complete records in input order.

def counting_sort(items, key, k):
    count = [0] * k
    for item in items:
        count[key(item)] += 1
    start = [0] * k
    total = 0
    for v in range(k):
        start[v] = total
        total += count[v]
    out = [None] * len(items)
    for item in items:
        v = key(item)
        out[start[v]] = item
        start[v] += 1
    return out

start[v] initially counts all items with keys smaller than v. After each placement, it advances to the next unused slot for that key. Because the input scan moves left to right, earlier equal-key records take earlier slots.

Trace the block positions

Use records (4, "a"), (1, "b"), (3, "c"), (4, "d"), (3, "e"), (0, "f"), (1, "g"). There are five possible keys, 0 through 4.

The counts are [1, 2, 0, 2, 2]. Their starting positions are [0, 1, 3, 3, 5]: key 3 starts after one key-0 item and two key-1 items. Key 2 has no items, so key 3 starts at the same index that an empty key-2 block would use.

Scan the input. Place a at 5, b at 1, c at 3, d at 6, e at 4, f at 0, and g at 2. The output is f, b, g, c, e, a, d, with keys 0, 1, 1, 3, 3, 4, 4. Each equal-key pair retains its order: b before g, c before e, and a before d.

An equivalent version stores cumulative end positions and scans records right to left. End positions combined with a left-to-right scan reverse the ties. The positions and scan direction must agree.

Include the range in the cost

Counting and placement scan n items; initialization and prefix sums scan k counters. Time and extra memory are both Θ(n+k) for this stable array version. When k=O(n), that is linear in the input size. If the range is huge, scanning its unused values can dominate everything.

One million scores from 0 through 100 need only 101 counters. In contrast, 100 values from 0 through one billion require 1,000,000,001 counters in a direct implementation. The range size is the maximum minus the minimum plus one, not the number of distinct keys observed.

For keys from -3 through 4, use index key - min_key; here k = 8. This preserves their order while making indexes nonnegative. Allocating only max_key slots for keys beginning at zero leaves no slot for the largest key.

For bare integers, repeating each value according to its count can reconstruct sorted output. For records, that shortcut loses the attached data and identities. Stable placement moves the actual records, which is also the form needed when counting sort supplies a radix-sort pass.

Key Takeaways

  • Counting sort uses integer keys as counter indexes.
  • Prefix sums give each key a starting output position.
  • Left-to-right placement from starts preserves equal-key order.
  • Time and extra memory are Θ(n+k), including unused key slots.
  • Shift negative keys and include both range endpoints when computing the counter count.
  • Reconstructing bare keys is insufficient for sorting records.

4.3 Sort one digit at a time

LSD radix sort orders keys by processing their least significant digit first. Each pass stably sorts the entire array by one digit, preserving the work of the earlier passes.

Follow three stable passes

In base 10, read [170, 45, 75, 90, 802, 24, 2, 66] as three-digit keys, including leading zeros such as 045 and 002.

  1. Stable sort by ones digit: [170, 90, 802, 2, 24, 45, 75, 66].
  2. Stable sort that result by tens digit: [802, 2, 24, 45, 66, 170, 75, 90].
  3. Stable sort by hundreds digit: [2, 24, 45, 66, 75, 90, 170, 802].

After the first pass, the last digit is ordered. After the second, the last two digits are ordered. On the third pass, all keys with hundreds digit 0 stay in the tens-pass order, which is already correct within that group. This is the invariant: after t passes, keys are ordered by their last t digits.

An unstable pass can reverse two records with equal current digits and destroy the ordering of their lower digits. Sorting the whole array from most significant to least significant also fails: the final pass would make the least significant digit the primary key.

Extract a digit and reuse stable counting sort

For nonnegative integer x, digit position t in base b is (x // b**t) % b. Position 0 is the least significant digit. Using the stable counting function for each pass gives:

def radix_sort(values, base=10):
    if not values:
        return []
    out = list(values)
    maximum = max(out)
    place = 1
    while place <= maximum:
        out = counting_sort(
            out, key=lambda x: (x // place) % base,
            k=base
        )
        place *= base
    return out

Here base is an integer at least 2 and inputs are nonnegative integers. Each counting pass completes before place changes. All-zero input is already sorted, so this implementation returns its copy without a digit pass. Negative keys can be offset into a nonnegative range before digit extraction.

Balance passes against counter storage

With d digits and base b, each pass costs Θ(n+b), giving Θ(d(n+b)) time and Θ(n+b) extra memory reused across passes. For positive maximum K, the digit count is ⌊log⁡bK⌋+1; represent zero with one digit when using a fixed digit count.

A 32-bit unsigned key needs four base-256 digits or two base-65,536 digits. Fewer passes require more counters. Base 256 extracts digit t with (x >> (8 * t)) & 255. If keys are below nc for a fixed positive integer c and the base is n, at most c passes give linear time under constant-time digit operations.

Fixed-length strings work similarly: stable-sort by the last character, then move left. Different lengths need a suitable padding rule or MSD radix sort, which groups by the most significant character and recursively sorts within each group. The choice depends on the key representation: arbitrary objects that expose only comparisons cannot supply counter indexes or digits.

Key Takeaways

  • LSD radix sort processes the whole array from least to most significant digit.
  • Each pass must be stable to retain the ordering of previously processed digits.
  • For d digits in base b, time is Θ(d(n+b)) and extra memory is Θ(n+b).
  • A larger base reduces passes while increasing counter storage.
  • Fixed-length strings can use character passes; MSD recursively sorts prefix groups.
5

Compare sorting and searching methods and choose the right one

Algorithm choice connects a cost analysis to a real workload. The fastest-looking growth rate can hide a large range, extra storage, expensive writes, or a missing stability guarantee. Compare the methods under the same conditions, account for existing order, and include the cost of preparing data for future searches. A useful justification names the task, the required properties, the chosen method, and the cost that follows.

5.1 Compare time, memory, and existing order

No single cost column describes all useful differences between algorithms. Compare methods under the same input and counting convention, then add the properties the task needs.

Read the main cost table

Here n is the item count, k the integer-key range size, d the digit count, and b the radix base. The sorting memory column gives extra storage beyond the input.

MethodTimeExtra memoryStable in the form taught?
SelectionΘ(n2) in all casesO(1)No
InsertionBest Θ(n); worst/average Θ(n2)O(1)Yes
Plain array mergeΘ(nlog⁡n) in all casesΘ(n)Yes
Randomized quicksortExpected O(nlog⁡n); worst Θ(n2)O(log⁡n) stack with smaller-side recursionNo
Stable countingΘ(n+k)Θ(n+k)Yes
LSD radixΘ(d(n+b))Θ(n+b)Yes

The quicksort expectation assumes random pivots, with three-way partitioning when keys repeat. Its linear all-equal case explains why the table uses expected upper-bound notation for general keys. For distinct keys, expected time is Θ(nlog⁡n). Ordinary two-call recursion can need a linear stack in a bad case.

For searches, linear search works on unsorted sequences in Θ(n) worst-case time. Iterative binary search takes Θ(log⁡n) worst-case time on a sorted random-access array. Both use constant extra space. The cost of establishing and maintaining sorted order belongs in a complete comparison.

Compare actual operation counts

For 1000 distinct items, selection sort always makes 499,500 key comparisons. Insertion sort makes 999 on sorted input and 499,500 on reversed input. Merge sort makes at most 8,977. Randomized quicksort averages about 10,986.

Those counts explain growth, but they are not timings. A comparison may involve an expensive custom key, and copying a large record may cost more than comparing its key. Cache behavior, memory allocation, and implementation overhead also affect measured time.

At sufficiently large sizes, an algorithm with quadratic growth loses to a comparable implementation with nlog⁡n growth. For very small pieces, insertion sort's simple loop often wins because its fixed overhead is low. Hybrid sorts use a cutoff and switch methods inside one sort.

Ask what existing order saves

Insertion sort adapts directly to few inversions. Selection sort still scans every suffix even when the input is already sorted. Plain merge sort still splits and copies through its levels. First- or last-pivot quicksort can become quadratic on sorted distinct keys.

Python's sorting uses Timsort, a stable adaptive merge-based algorithm. It detects existing runs, reverses descending runs with tie handling that preserves stability, extends short runs with insertion sorting, and merges them. Sorted input takes linear time; the worst-case bound is O(nlog⁡n). Long useful runs can save work that a plain merge sort would repeat.

Calling counting or radix sort "linear" also needs its parameters. A huge range makes counting expensive; a long key requires many radix passes. Keep these conditions beside a bound instead of reducing the decision to a ranking by algorithm name.

Key Takeaways

  • Compare the same cost case and count the same operations across methods.
  • Stable counting and radix costs include range, base, and digit parameters.
  • Quicksort expectations require the pivot and duplicate-handling strategy.
  • Existing order helps adaptive methods but can harm fixed-pivot quicksort.
  • Timings also depend on comparisons, data moves, memory access, and constant overhead.

5.2 Choose for the workload and requirements

A good choice begins with the workload: what data is stored, how often it is searched or changed, and which output properties matter. State these facts before choosing an algorithm.

Start with the library and check requirements

In everyday Python, sorted(items, key=...) or items.sort(key=...) is a useful default. The implementation is well tested, stable, and adaptive. A hand-written method earns its place when it exploits special key structure or serves a learning task.

If equal-key records must retain arrival order, require a stable sort. For 500,000 orders already listed in time order, one stable sort by customer groups each customer's orders without disturbing their time order. Integer customer keys from 0 through 9,999 also fit stable counting sort: Θ(n+k) time with k=10,000. Plain selection sort or quicksort could scramble ties.

If worst-case time must be bounded for potentially hostile input, merge sort guarantees Θ(nlog⁡n). Random pivots improve quicksort's expected behavior but do not give that guarantee. Under tight extra-memory limits, quicksort with smaller-side recursion uses only a logarithmic stack, while insertion sort uses constant space for small or nearly sorted inputs. Linked lists favor merging because it can follow and relink nodes without random access.

Include the cost of sorting before searching

For one million items, estimate sorting at about 20 million comparisons and each binary search at at most 20 middle probes. If targets are absent, a linear scan checks all one million items each time. Five scans cost about 5 million comparisons, so sorting first would spend more. Around 20 such lookups brings the two approaches close.

For successful searches with targets spread evenly through the list, a scan averages about 500,000 comparisons. The approximate break-even shifts to 40 lookups. At 100 such lookups, linear scanning costs about 50 million comparisons, while sorting once plus binary searches costs about 20 million. These are workload estimates, not a universal fixed cutoff.

More generally, compare qL with S+qB, where q is the lookup count, L the average linear-search cost, S the one-time sort cost, and B the binary-search cost. Sorting pays off when its initial cost is recovered by the savings on enough lookups. If the original order matters, also account for keeping a copy or original indexes.

Match the representation and operations

For membership alone, a hash set offers expected constant-time lookups. A sorted array is useful for closed-range counts, nearest values, successors, ordered output, and direct access to its minimum and maximum. The required operation can decide more than a raw membership timing.

Nearly sorted data or a trickle of arriving values suits insertion. bisect.insort finds the position logarithmically, but shifting a Python list still costs linear time per insertion in the worst case. Small-range integers suit counting sort; fixed-width integer or string keys with few digits suit radix sort. Comparison-only object keys need a comparison sort.

A concrete justification might be: "Ten million 32-bit sensor readings, with enough auxiliary memory: base-256 LSD radix sort needs four stable passes and linear extra storage." If that memory is unavailable, randomized three-way quicksort with smaller-side recursion gives expected O(nlog⁡n) time and a logarithmic stack. State the chosen tradeoff along with its cost.

Key Takeaways

  • Choose from the data representation, required operations, stability, memory, and time guarantees.
  • Library sorting is the everyday default; special key structure can justify counting or radix sort.
  • Compare all lookup costs with the one-time cost of sorting.
  • Binary-search insertion still needs linear worst-case shifts in an array.
  • Give a concrete reason and cost for the chosen method.

Sorting and Searching examples

5 Walkthroughs

1

From a scan to a search boundary

16 steps
Trace searches, keep bounds consistent, and turn insertion points into useful answers.
  1. 1
    IntroductionChoose what the search must return

    A search may need any match, the first match, or an exact boundary (an insertion point). Those are different tasks.

    Start with a scan of unsorted data, then use sorted order to eliminate whole ranges, which is binary search. Keep track of what each probe has ruled out. That record of remaining possibilities, the invariant that keeps the bounds safe, will also explain how to count duplicate values and find a threshold without testing every position.

  2. 2
    ExampleScan until the first match

    Search [42, 17, 8, 99, 23] for 99.

    The scan rejects 42, then 17, then 8. It accepts 99 at index 3 after four equality tests. Searching for 5 instead rejects all five values before returning failure.

    The failure return belongs after the scan. A single mismatch establishes only that one position is wrong, not that the whole sequence lacks the target.

  3. 3
    Key InsightCount the positions actually visited

    A target in the first position needs one comparison. A target in the last position, or no match at all, needs n comparisons.

    If a successful target is equally likely to occupy each position, average the costs 1 through n to get (n+1)/2. The uniform-position assumption matters: a frequently requested value near the front can make an actual workload much cheaper.

  4. 4
    ChallengePlace the failure return

    A scan of [14, 29, 6, 38] returns -1 immediately when its first item differs from target 38. Where should that return go, and what should a corrected search return?

    ---reveal---

    Put return -1 after the loop. The corrected scan checks all four items and returns index 3. The early return confuses one rejected position with absence from the entire list.

  5. 5
    ExplanationKeep all possible matches inside the bounds

    For inclusive binary search, begin with lo = 0 and hi = len(a) - 1.

    The invariant is: if a match exists, one remains in the candidate range. A middle value below the target rules out every position through that middle. A middle value above it rules out every position from the middle onward. This conclusion comes from sorted order, not from numeric spacing between values.

  6. 6
    ExampleMake the first middle probe

    Use [3, 8, 15, 21, 34, 42, 57, 66, 79, 91], target 57, with bounds 0 through 9.

    The lower middle is index 4, value 34. It is too small, so set lo = 5; no earlier position can hold 57. The next middle is index 7, value 66. It is too large, so set hi = 6. The remaining range has only indexes 5 and 6.

  7. 7
    ExampleFinish with a one-item range

    Bounds 5 through 6 give middle index 5, value 42. Move lo to 6.

    Bounds 6 through 6 still describe a valid candidate: one item. Probing it finds 57. The four middle values were 34, 66, 42, and 57.

    An inclusive loop must allow lo == hi. Using while lo < hi here would stop just before the successful final probe.

  8. 8
    TipSeparate shrinking from copying

    Pass the original array and bounds to recursive binary search. Creating a slice copies the selected half and gives it new local indexes.

    Across a long search path, half-size copies total linear work even though the number of probes is logarithmic. Iterative bounds avoid both copying and recursive stack space. On a linked list, walking to middle nodes is another cost that a probe count alone hides.

  9. 9
    ChallengeTrace an absent target

    Inclusive binary search uses lower middles on [5, 13, 18, 26, 35], looking for 20. What values are probed, and what final bounds establish absence?

    ---reveal---

    Probe 18 at index 2, then 26 at index 3. The updates give lo = 3 and hi = 2. The candidate range is empty, so return failure. A final insertion point of 3 would lie between 18 and 26.

  10. 10
    ExplanationKeep searching when keys tie

    A plain binary search may stop at any duplicate. For the first position at least x, use a half-open range with hi = len(a).

    If a[mid] < x, move lo past mid. Otherwise move hi to mid, keeping equality on the boundary’s right side. At termination, everything before the returned position is smaller, and everything from it onward is at least x.

  11. 11
    ExampleUse both ends of an equal block

    In [1, 2, 2, 2, 5, 7], the left insertion point for 2 is 1 and the right insertion point is 4.

    The equal-key block occupies indexes 1, 2, and 3, so its size is 4 minus 1, or 3. The right boundary is a position after the last match. For target 4, both insertion points are 4 even though the target is absent: boundaries are not membership results.

  12. 12
    ChallengeCount an inclusive range

    In [1, 4, 4, 7, 10, 10, 13], how many values lie from 4 through 10, including both endpoints? Give the two boundary positions.

    ---reveal---

    The left insertion point of 4 is 1; the right insertion point of 10 is 6. Their difference is five. Using the left point for the high endpoint would stop before its equal values and exclude both copies of 10.

  13. 13
    ExampleInspect only the closest neighbors

    On [3, 8, 15, 21, 34, 42, 57, 66, 79, 91], the left insertion point of 50 is index 6.

    Only the neighbors 42 and 57 can be nearest: every earlier value is farther left, and every later value is farther right. Their distances are 8 and 7, so choose 57. At an endpoint, one neighbor may not exist; check its index before reading it.

  14. 14
    ConnectionSearch a monotone test

    You can halve a domain even when no array is stored. For nonnegative integers, the test x * x >= 200 is false through 14 and true from 15 onward.

    A true middle test retains the middle as a possible first success and discards larger candidates. A false test discards the middle and everything smaller. The same logic finds the first faulty version when every later version also contains the fault.

  15. 15
    ChallengeCombine preparation and a boundary query

    A program stores unsorted integer readings and must repeatedly count those in a closed range. How can sorting and boundary searches support the counts, and what changes if new readings arrive?

    ---reveal---

    Sort once, then subtract the low value’s left insertion point from the high value’s right insertion point for each query. Each count needs logarithmic search work. New readings must keep the array sorted; finding an insertion point is logarithmic, but opening its slot can require linear shifts.

  16. 16
    RecapCheck the search contract

    For a scan, check whether failure is reported only after all candidates are rejected. For binary search, check sorted order, bounds, and progress on a one-item range.

    For a boundary result, ask whether the position proves membership or needs a value check. When applying binary search to a condition, establish that a true result stays true as the input increases.

2

Build and preserve a sorted prefix

18 steps
Trace selection and insertion, test preservation, and use stable ties to build multi-key order.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrack records as well as keys
  2. 2
    ExplanationCheck two obligations
  3. 3
    ChallengeTest a plausible-looking result
  4. 4
    ExplanationFind a minimum before moving it
  5. 5
    ExampleComplete the first selection passes
  6. 6
    Key InsightFew swaps do not mean few comparisons
  7. 7
    ChallengePredict the next fixed position
  8. 8
    ExplanationSave the next item before shifting
  9. 9
    ExampleInsert one item, then the next
  10. 10
    ExampleFollow the longer insertion
  11. 11
    Key InsightMeasure the disorder removed
  12. 12
    ChallengeCount shifts from the input
  13. 13
    ExplanationMake equal keys visibly different
  14. 14
    ExampleEstablish a secondary order first
  15. 15
    ChallengeChoose the order of stable passes
  16. 16
    ConnectionSupply a tie breaker explicitly
  17. 17
    ChallengePreserve a useful existing order
  18. 18
    RecapInspect the invariant and the ties
3

Merge halves and partition around pivots

17 steps
Work through both divide-and-conquer sorts and diagnose what controls quicksort’s cost.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionPut the main work on either side of recursion
  2. 2
    ExplanationConsume the smaller front item
  3. 3
    ExampleBegin a merge
  4. 4
    ExampleCopy the remaining tail
  5. 5
    Key InsightCount work across each level
  6. 6
    ChallengeMerge and preserve the tail
  7. 7
    ExplanationGrow a pivot-relative region
  8. 8
    ExampleMove small keys across the boundary
  9. 9
    ExampleFix the pivot and leave the sides
  10. 10
    TipCheck what a partition returns
  11. 11
    ChallengePartition without overclaiming
  12. 12
    ExplanationRead the recursion shape
  13. 13
    ConnectionRandomness changes the expectation
  14. 14
    Key InsightRemove equal keys from recursion
  15. 15
    ChallengeSeparate stack space from running time
  16. 16
    ChallengeSelect a guarantee the task needs
  17. 17
    RecapInspect the remaining subproblems
4

Use the comparison limit and integer structure

16 steps
Derive the lower bound, place records with counts, and build radix order with stable passes.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk what information the method reads
  2. 2
    ExplanationMake comparisons into branches
  3. 3
    ExampleTurn leaves into a depth bound
  4. 4
    Key InsightKeep the model and case attached
  5. 5
    ChallengeTest a claimed comparison bound
  6. 6
    ExplanationTurn frequencies into block starts
  7. 7
    ExamplePlace records in their encounter order
  8. 8
    TipInclude unused key values in the cost
  9. 9
    ChallengeCompute an offset and starts
  10. 10
    ExplanationBuild order from the least significant digit
  11. 11
    ExampleComplete the first digit pass
  12. 12
    ExampleKeep earlier order inside the next ties
  13. 13
    ChallengeApply two stable passes
  14. 14
    ConnectionTrade counter space for fewer passes
  15. 15
    ChallengeUse key structure to change the bound
  16. 16
    RecapCheck what makes the speed possible
5

Choose for a complete workload

11 steps
Compare the same costs, include preparation, and justify a method against the task’s requirements.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionChoose the operation before the algorithm
  2. 2
    ExampleCompare input order under one size
  3. 3
    ConnectionGive existing order a role
  4. 4
    ChallengeDistinguish growth from a small-input timing
  5. 5
    ExplanationAccount for the sort before the searches
  6. 6
    ExampleEstimate a repeated-lookup workload
  7. 7
    ChallengeCompare both complete plans
  8. 8
    ExampleLet stability decide a record sort
  9. 9
    TipInclude maintenance and memory
  10. 10
    ChallengeWrite a complete justification
  11. 11
    RecapMake the decision reviewable

Sorting and Searching practice questions

50 Practice Questions in 5 sets

Set 1: Trace searches and sorting steps10 Practice Questions

Question 1 of 10

During a stable merge, the two front records have equal keys. Which side supplies the next record?
  1. The longer half supplies it.
  2. The left half supplies it.
  3. The shorter half supplies it.
  4. The right half supplies it.
Show answerHide answer
Answer: B
The left-half record appeared before the right-half record in the original input, so it must be copied first to preserve tie order. Taking from the right can still produce sorted keys but breaks stability. The lengths of the two halves do not determine the tie rule.

Question 2 of 10

A comparison sort must distinguish the 5040 relative orders of seven distinct keys. What minimum worst-case comparison count follows from its binary decision tree?
  1. 12 comparisons
  2. 14 comparisons
  3. 11 comparisons
  4. 13 comparisons
Show answerHide answer
Answer: D
Twelve binary comparison levels allow at most 4096 leaves, which cannot distinguish 5040 relative orders. Thirteen levels allow up to 8192, so the lower bound is thirteen. Twelve comparisons would leave some possible orders indistinguishable; the bound applies to the worst case, not every input.

Question 3 of 10

For [5, 2, 4], how many inversions are present?
  1. 2 inversions
  2. 3 inversions
  3. 0 inversions
  4. 1 inversion
Show answerHide answer
Answer: A
The earlier value 5 exceeds both later values 2 and 4, giving two inverted pairs. The pair 2 and 4 is already in order. Counting only adjacent out-of-order pairs would find just 5 and 2, but inversions include nonadjacent positions such as 5 and 4.

Question 4 of 10

Method A takes 80*n basic operations; method B takes n*n. At n = 16, which uses fewer operations, and which has better growth for large n?
  1. B uses fewer now; B has better growth.
  2. A uses fewer now; A has better growth.
  3. B uses fewer now; A has better growth.
  4. A uses fewer now; B has better growth.
Show answerHide answer
Answer: C
At size 16, A uses 1280 operations while B uses 256, so B is cheaper at that size. A grows linearly and eventually wins against quadratic growth. Choosing A for the small case from its growth class alone ignores the stated constant factor of 80.

Question 5 of 10

How many counter slots are required to sort integer keys from -6 through 9 by offset counting sort?
  1. 6 slots
  2. 16 slots
  3. 10 slots
  4. 15 slots
Show answerHide answer
Answer: B
The range includes both endpoints, so its size is 9 - (-6) + 1 = 16. Subtracting the minimum maps -6 to index 0 and 9 to index 15. Fifteen slots cover only indexes 0 through 14, leaving no slot for the maximum key.

Question 6 of 10

An integer-key sorting algorithm runs in linear time on keys in 0..n-1. Why is this compatible with the comparison-sorting lower bound?
  1. It changes the number of input items.
  2. It has no worst-case input order.
  3. It can use key values as indexes.
  4. It needs no storage for its output.
Show answerHide answer
Answer: C
The lower bound applies when pairwise comparisons are the only source of key-order information. Directly indexing counters by integer values uses additional structure, so that model does not describe the algorithm. Linear time is not explained by eliminating worst cases or by a claim of zero storage.

Question 7 of 10

Sorted records are [(2017, "a"), (2021, "b"), (2021, "c"), (2026, "d")]. What argument to bisect_left(records, x, key=lambda r: r[0]) finds the first record from 2021?
  1. x = 2021
  2. x = 1
  3. x = (2021, "b")
  4. x = "2021"
Show answerHide answer
Answer: A
The key function extracts integer years from the stored records, so the search value must already be the integer year 2021. Passing a whole record treats bisect like insort, whose key handling differs. The resulting insertion position is 1, but that position is an output, not the search key.

Question 8 of 10

How many key comparisons does the ordinary front-by-front merge of [1, 6, 12] and [3, 8] make?
  1. 6 comparisons
  2. 5 comparisons
  3. 3 comparisons
  4. 4 comparisons
Show answerHide answer
Answer: D
The comparisons select 1, then 3, then 6, then 8. The right list is then empty, so 12 is appended without a key comparison. Counting five treats that tail copy as another comparison, although its position is already established by the sorted input lists.

Question 9 of 10

A sorted Python list receives one new item through bisect.insort. What is the worst-case time for the whole insertion?
  1. Θ(nlog⁡n)
  2. Θ(1)
  3. Θ(log⁡n)
  4. Θ(n)
Show answerHide answer
Answer: D
Finding the insertion position takes logarithmically many comparisons, but making room can shift all n existing items. Those shifts dominate the complete operation, giving linear worst-case time. Reporting only logarithmic time counts the boundary search and leaves out the list update it enables.

Question 10 of 10

Last-pivot Lomuto quicksort sorts [8, 3, 7, 2, 6, 5], excluding each fixed pivot from recursive calls. How many pivot comparisons does the complete sort make?
  1. 8 comparisons
  2. 15 comparisons
  3. 7 comparisons
  4. 9 comparisons
Show answerHide answer
Answer: A
The first partition uses five comparisons and leaves [3, 2] to the left of 5 and [8, 6, 7] to the right. Sorting those sides needs one and two more pivot comparisons, giving eight. Counting only seven omits the two-item left partition, which must still put 2 before 3.
Set 2: Explain work and preserve key order10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Inclusive binary search has lo = 0, hi = 6, and target 25 in [4, 10, 16, 22, 28, 34, 40]. What bounds remain after its first unsuccessful probe?
  1. lo = 0, hi = 3
  2. lo = 3, hi = 6
  3. lo = 4, hi = 6
  4. lo = 0, hi = 2
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does Python return from items.sort() after sorting the list successfully?
  1. None
  2. The original list
  3. The sorted list
  4. The number of swaps
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A numeric-key sort transforms [(2, "a"), (1, "b"), (2, "c"), (1, "d")] into [(1, "d"), (1, "b"), (2, "a"), (2, "c")]. Is it a correct stable sort of these records?
  1. Correctly sorted and stable, but not preserved.
  2. Preserved and stable, but not correctly sorted.
  3. Correctly sorted, preserved, and stable.
  4. Correctly sorted and preserved, but unstable.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

For sorted [5, 8, 8, 12, 16, 16, 19, 23], how many values lie in the closed range from 8 through 16?
  1. 6 values
  2. 5 values
  3. 4 values
  4. 3 values
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

An application needs stable sorting with a worst-case n log n bound for arbitrary comparable records. It has room for an output buffer. A developer proposes randomized in-place quicksort because it is fast on average. What change meets the requirements directly?
  1. Use selection sort with the first minimum on ties.
  2. Keep quicksort and use smaller-side recursion only.
  3. Keep quicksort and choose random pivots more often.
  4. Use stable merge sort with left-on-ties merging.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What array remains after two complete selection-sort passes on [24, 6, 19, 3, 12]?
  1. [3, 6, 19, 24, 12]
  2. [6, 24, 19, 3, 12]
  3. [3, 12, 19, 24, 6]
  4. [3, 6, 12, 19, 24]
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An array merge sort uses one reusable output buffer and recursive index bounds. What are its worst-case time and total extra-memory growth rates?
  1. Θ(n) time, Θ(nlog⁡n) space.
  2. Θ(nlog⁡n) time, Θ(n) space.
  3. Θ(nlog⁡n) time, Θ(log⁡n) space.
  4. Θ(n2) time, Θ(n) space.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

In sorted a = [2, 4, 4, 4, 9, 11], what are bisect_left(a, 4) and bisect_right(a, 4)?
  1. 2 and 4
  2. 2 and 3
  3. 1 and 4
  4. 1 and 3
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A singly linked list of a million records must be stably sorted by a comparison-only key with a worst-case n log n time guarantee. What method fits, and why?
  1. Merge sort: relink runs and take right keys on ties.
  2. Insertion sort: relink records into a stable prefix.
  3. Merge sort: relink runs and take left keys on ties.
  4. Quicksort: random pivots with original-index tie breakers.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Three-character keys are BAA, ABA, AAB, BBA. Stable LSD radix passes use alphabetic character order. What order follows the first two passes, before the leading-character pass?
  1. BAA, AAB, ABA, BBA
  2. AAB, ABA, BAA, BBA
  3. BBA, ABA, AAB, BAA
  4. BAA, ABA, BBA, AAB
Show answerHide answer

Save this lesson to see this answer.

Set 3: Diagnose algorithms and their costs10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A sort of [8, 3, 8, 1] produces [1, 3, 8]. What correctness requirement has failed?
  1. It failed to avoid adjacent equal keys.
  2. It failed to put keys in ascending order.
  3. It failed to choose comparable numeric keys.
  4. It failed to preserve item multiplicities.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Every quicksort partition splits distinct keys in a fixed 9-to-1 proportion. What asymptotic total time follows?
  1. Θ(log⁡n)
  2. Θ(nlog⁡n)
  3. Θ(n2)
  4. Θ(n)
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What order remains after the first stable ones-digit pass of base-10 LSD radix sort on [42, 17, 31, 12, 27]?
  1. [31, 42, 12, 17, 27]
  2. [31, 12, 42, 17, 27]
  3. [17, 27, 31, 42, 12]
  4. [12, 17, 27, 31, 42]
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A guarded selection sort processes 9 distinct values. How many key comparisons does it make, and what is its maximum number of actual swaps?
  1. 16 comparisons; at most 8 swaps.
  2. 36 comparisons; at most 36 swaps.
  3. 36 comparisons; at most 8 swaps.
  4. 45 comparisons; at most 8 swaps.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Records arrive in timestamp order and must be grouped by integer category 0..127, retaining that order within categories. There are two million records and room for an output array. What specialized method meets these requirements with linear time?
  1. Stable counting sort by category.
  2. Lomuto quicksort by category only.
  3. Unstable counting placement by category.
  4. Selection sort by timestamp only.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Inclusive binary search uses the lower middle and searches [2, 9, 14, 20, 27, 33, 46, 58] for 33. What sequence of middle values does it inspect?
  1. 20, 27, 33
  2. 20, 46, 33
  3. 27, 33
  4. 20, 33
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Insertion sort is about to insert 5 into the sorted prefix of [2, 7, 10, 5, 13]. What is the array after that insertion?
  1. [2, 5, 10, 7, 13]
  2. [2, 5, 7, 10, 13]
  3. [2, 7, 5, 10, 13]
  4. [2, 7, 10, 13, 5]
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A last-pivot Lomuto quicksort recurses on lo..p and p+1..hi. What occurs on [3, 5, 7], and what change repairs it?
  1. It stops too soon; allow recursion when lo == hi.
  2. It skips the first key; include p on the right.
  3. It repeats the whole range; exclude p on the left.
  4. It reverses the keys; swap the two recursive calls.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Insertion sort shifts only larger values and counts only value comparisons, not bounds checks. How many shifts and value comparisons does it make on [4, 1, 3, 2]?
  1. 4 shifts and 6 comparisons.
  2. 5 shifts and 6 comparisons.
  3. 4 shifts and 4 comparisons.
  4. 6 shifts and 6 comparisons.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Integer capacity c is sufficient exactly when c*c >= 90, with allowed capacities 0..20. A first-true search uses lo = 0, hi = 21, lower middles, and hi = mid on true. What capacity is returned and how many condition tests occur?
  1. Capacity 11, after 3 tests.
  2. Capacity 10, after 4 tests.
  3. Capacity 9, after 4 tests.
  4. Capacity 10, after 5 tests.
Show answerHide answer

Save this lesson to see this answer.

Set 4: Choose methods and justify tradeoffs10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Lomuto partition uses the final value as pivot. What array and pivot index result from one partition of [7, 2, 6, 3, 5]?
  1. [3, 2, 5, 7, 6], index 1
  2. [2, 3, 5, 6, 7], index 2
  3. [2, 3, 5, 7, 6], index 2
  4. [2, 3, 6, 7, 5], index 4
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What extra-data property does iterative binary search need, beyond the equality comparisons sufficient for a linear scan?
  1. Equal spacing between every pair of values.
  2. Sorted order consistent with its comparisons.
  3. A number of items that is a power of two.
  4. A different value stored at every position.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Counting sort receives keys [2, 0, 2, 1, 3, 1] in range 0..3. What initial starting positions should its stable output blocks use?
  1. [0, 1, 3, 5]
  2. [1, 2, 2, 1]
  3. [1, 3, 5, 6]
  4. [0, 1, 2, 4]
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

An unstable sort can compare tuple keys, and extra storage is available. Records need ascending priority with original input order retained among equal priorities. What key construction achieves that?
  1. (priority, final_index)
  2. (priority, -original_index)
  3. (priority, original_index)
  4. (original_index, priority)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A function returns a matching index or -1. It searches [26, 9, 14] for 8, then the caller immediately prints a[result]. What happens?
  1. It raises ValueError.
  2. It raises IndexError.
  3. It prints -1.
  4. It prints 14.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

Records are [("A", 2, 7), ("B", 1, 9), ("C", 2, 5), ("D", 1, 6)], holding name, group, and score. A stable sort by score descending is followed by a stable sort by group ascending. What name order results?
  1. A, C, B, D
  2. B, D, A, C
  3. B, A, D, C
  4. D, B, C, A
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A quicksort must handle sorted distinct inputs and arrays dominated by one repeated key, while keeping nested calls logarithmic. What combination addresses all three risks?
  1. Random pivots, three-way partition, smaller-side recursion.
  2. Random pivots, two-way partition, smaller-side recursion.
  3. Last pivots, three-way partition, two-side recursion.
  4. Median-of-three, two-way partition, two-side recursion.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A collection has 2048 items. Sorting is estimated to cost 22,528 comparisons, each binary lookup at most 12 probes, and every linear lookup examines all items. With 20 absent-target lookups, what comparison-cost plan is cheaper under this model?
  1. Scan directly: 24,576 tests versus 45,056.
  2. Scan directly: 22,528 tests versus 40,960.
  3. Sort first: at most 40,960 tests versus 45,056.
  4. Sort first: at most 22,768 tests versus 40,960.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Inclusive binary search uses while lo < hi and otherwise the usual bounds and updates. It searches [6, 15, 24] for 24. What happens?
  1. It finds index 2 after two probes.
  2. It loops forever after one probe.
  3. It returns failure after one probe.
  4. It raises an indexing error at index 3.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Quicksort uses random pivots and two-way Lomuto partitioning on an all-equal array. It now recurses only on the smaller side and loops on the larger side. What worst-case time and stack bounds result?
  1. Linear time and Θ(n) stack.
  2. Quadratic time and O(log⁡n) stack.
  3. Linear time and O(log⁡n) stack.
  4. Quadratic time and Θ(n) stack.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Transfer methods to new constraints10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

Linear search checks [18, 7, 31, 12, 7] from the front. What index does it return for target 7?
  1. 2
  2. 5
  3. 1
  4. 4
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Unsigned 24-bit keys are sorted by LSD radix sort in base 256. How many passes and counter slots per pass are needed?
  1. 4 passes and 256 slots.
  2. 8 passes and 24 slots.
  3. 3 passes and 255 slots.
  4. 3 passes and 256 slots.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A static collection must support nearest-value queries and counts inside closed numeric intervals. What structure supports both with logarithmic query work after preparation?
  1. A sorted random-access array.
  2. A hash set of the same values.
  3. A linked list in arrival order.
  4. An unsorted random-access array.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What running time does ordinary last-pivot Lomuto quicksort have on an already sorted array of distinct keys?
  1. Θ(log⁡n)
  2. Θ(n2)
  3. Θ(nlog⁡n)
  4. Θ(n)
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A proposed comparison sort claims at most six comparisons for every ordering of five distinct keys, but uses four comparisons on sorted input. What follows from the decision-tree model?
  1. The worst-case claim fails; the best-case claim may hold.
  2. Both claims fail because every input needs seven comparisons.
  3. Both claims hold because six exceeds the item count.
  4. The worst-case claim holds; the best-case claim fails.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

For list a = [8, 3, 11, 3, 6], a loop processes targets [3, 6, 9]. For each target it first tests x in a; only when that succeeds does it call a.index(x). How many item-equality comparisons occur in total?
  1. 12 comparisons
  2. 14 comparisons
  3. 24 comparisons
  4. 19 comparisons
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A stable selection-sort variant removes each suffix minimum, shifts all intervening items one position right, then places the minimum. On [4, 1, 3, 2], how many key comparisons and intervening-item shifts occur, excluding minimum-placement writes?
  1. 6 comparisons and 6 shifts.
  2. 6 comparisons and 3 shifts.
  3. 6 comparisons and 4 shifts.
  4. 4 comparisons and 4 shifts.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

An insertion sort changes its loop test from a[j] > x to a[j] >= x. It sorts by number only. What final order results from [(3, "u"), (1, "v"), (3, "w"), (1, "z")]?
  1. [(1, "z"), (1, "v"), (3, "u"), (3, "w")]
  2. [(1, "z"), (1, "v"), (3, "w"), (3, "u")]
  3. [(1, "v"), (1, "z"), (3, "u"), (3, "w")]
  4. [(1, "v"), (1, "z"), (3, "w"), (3, "u")]
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A list has 4096 distinct items. Sorting costs 49,152 comparisons and binary lookup costs at most 13 probes. There will be 12 successful lookups, each equally likely to target any position. Which plan has lower expected comparison work under this model?
  1. Sort first: 49,308 versus 49,152.
  2. Linear scans: 49,152 versus at most 49,308.
  3. Sort first: 24,582 versus 49,308.
  4. Linear scans: 24,582 versus at most 49,308.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Stable counting sort uses exclusive cumulative end positions, decrements the selected end, and writes there. It scans [(2, "a"), (0, "b"), (2, "c"), (0, "d")] left to right. What output does this produce?
  1. [(0, "d"), (0, "b"), (2, "c"), (2, "a")]
  2. [(0, "d"), (0, "b"), (2, "a"), (2, "c")]
  3. [(0, "b"), (0, "d"), (2, "c"), (2, "a")]
  4. [(0, "b"), (0, "d"), (2, "a"), (2, "c")]
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

68 Key Terms, each with its definition

A

Adaptive sort
An adaptive sort reduces its work when useful ordering is already present in the input, such as few inversions or long runs.
Insertion sort shifts very little on a list in which only a few neighboring values are out of order.
Asymptotic optimality
Asymptotic optimality means matching a problem’s lower-bound growth rate, without requiring the best constant or fastest small case.
Merge sort matches the comparison model’s n log n worst-case growth while still needing an array buffer.

B

Binary search
A binary search probes the middle of a sorted candidate range and discards the side that cannot contain the target.
Searching a million sorted integer identifiers takes at most twenty middle-element probes.
Bottom-up merge sort
Bottom-up merge sort repeatedly merges neighboring runs of doubling sizes, building a sorted result without recursive calls.
Its passes combine single items into pairs, pairs into groups of four, and so on until one run remains.
Break-even point
A break-even point is the workload size where the savings from cheaper later operations recover a one-time preparation cost.
Successful targets near the front make scans cheaper, so more lookups may be needed to repay a sort.

C

Candidate range
A candidate range is the set of positions still allowed to contain a search result after earlier probes have ruled out others.
If the middle value is too small, the next candidate range begins one position after that middle.
Closed interval
A closed interval includes both endpoint values, so its count must retain every occurrence equal to either boundary.
Counting readings from 12 through 18 includes all copies of 12 and all copies of 18 in the sorted data.
Comparison lower bound
A comparison lower bound states unavoidable comparison work for every algorithm in the model, under the specified cost case.
The worst-case bound applies even to a new comparison-sort design whose implementation is not yet known.
Comparison sort
A comparison sort learns the ordering of its input through comparisons between pairs of keys, rather than direct key indexing.
Merge sort compares front keys, so its worst case is subject to the comparison-sorting lower bound.
Constant factor
A constant factor scales an operation count without changing its asymptotic growth class, but can matter at practical input sizes.
Allocating a buffer can make a small merge sort slower than insertion even though its growth rate is better.
Counting sort
Counting sort orders suitable integer-key items by counting each key and using those totals to determine output positions.
A million values in 0 through 255 need only 256 counters in addition to their stable output storage.

D

Decision tree
A decision tree represents comparisons as internal questions and their outcomes as branches ending in completed rearrangements.
A sort execution follows one root-to-leaf path whose length counts the comparisons on that input.
Digit extraction
Digit extraction isolates one position of a key using division and remainder, or shifts and masks for a power-of-two base.
For nonnegative x, (x // 100) % 10 extracts the hundreds digit without comparing x with another key.
Divide and conquer
Divide and conquer solves a problem by forming smaller problems of the same kind and combining or organizing their solutions.
Merge sort performs its main combining work after the recursive calls have returned sorted halves.

E

Expected running time
An expected running time is a probability-weighted average of execution costs, such as the average over random pivot choices.
A randomized sort can have expected n log n time even though a rare sequence of pivots takes quadratic time.

H

Half-open range
A half-open range includes its lower endpoint and excludes its upper endpoint, making equal bounds an empty range.
Boundary search can start at [0, n) and return n without ever reading the nonexistent item at n.
Hoare partitioning
Hoare partitioning scans inward from both ends, swaps misplaced items, and returns a boundary separating two recursive ranges.
Its left recursive range includes the returned boundary, unlike recursion around a Lomuto pivot index.
Hybrid sort
A hybrid sort combines methods within one implementation, using each where its cost or structure fits the current subproblem.
A quicksort implementation can switch to insertion sort once a partition becomes very short.

I

In-place sort
An in-place sort, under the strict space definition, uses only constant auxiliary storage beyond its input array.
Insertion sort saves an item and indexes, while array merge sort needs a separate linear output buffer.
Inclusive bounds
Inclusive bounds are endpoints that both belong to a range, so equal lower and upper indexes still describe one item.
An inclusive search continues when lo == hi because the last candidate has not yet been ruled out.
Insertion sort
Insertion sort expands a sorted prefix by saving the next item, shifting larger prefix items right, and filling the resulting gap.
A newly arriving timestamp can be inserted into the ordered sequence of timestamps already received.
Inversion
An inversion is a pair of positions where the earlier item has a larger key than the later item, violating their sorted order.
In [4, 1, 3], the pairs (4, 1) and (4, 3) account for the two shifts needed by insertion sort.

K

Key offset
A key offset subtracts the minimum possible key to map an integer range onto nonnegative counter indexes without changing order.
With minimum key -4, an item whose key is -1 uses counter index 3 instead of a negative Python index.
Key range size
The key range size is the number of integer values between the minimum and maximum allowed keys, including both endpoints.
Keys from -2 through 5 span eight possible values, even if only two of those values occur in the input.

L

Leftmost insertion point
The leftmost insertion point is the first sorted-array position with a key at least as large as the target, or the array end.
For [2, 6, 6, 9], the leftmost insertion point of 6 is index 1, just before the equal block.
Linear search
A linear search examines sequence items one at a time, stopping at a match or after all available items have been checked.
An unsorted list of sensor identifiers can be scanned directly when only one lookup is needed.
Lomuto partitioning
Lomuto partitioning scans nonpivot items, grows a small-key region, and swaps its end pivot into its final sorted position.
The returned pivot index is excluded from both recursive calls because that item is already fixed.
Loop invariant
A loop invariant is a statement that holds before the first iteration and is preserved by each iteration to establish correctness.
Selection sort keeps a prefix containing the smallest items in final order before each new suffix scan.
LSD radix sort
LSD radix sort stably sorts all keys by successive digits, beginning at the least significant position and moving toward the most.
A ones-digit pass followed by a stable tens-digit pass orders two-digit nonnegative integer keys.

M

Median-of-three
Median-of-three chooses the middle-valued key among the first, middle, and last candidates as a quicksort pivot heuristic.
On sorted distinct keys, the middle candidate avoids the extreme pivot chosen by a fixed-end rule.
Merge
A merge combines two already sorted sequences into one sorted sequence, consuming their front items and then their remaining tail.
When the left input runs out, the merge appends the right tail without further key comparisons.
Merge sort
Merge sort recursively sorts smaller halves and combines their ordered results by repeatedly selecting the smaller front item.
Dividing seven records into groups of three and four still gives shrinking recursive problems.
Monotone condition
A monotone condition for first-true search is false before a boundary and true afterward, without changing back to false.
A capacity test suits binary search when increasing sufficient capacity can never make it insufficient.
MSD radix sort
MSD radix sort groups keys by their most significant digit or character and recursively sorts within each resulting group.
String keys with the same initial character are ordered by their next characters inside that prefix group.

N

Nondecreasing order
Nondecreasing order means each key is at least as large as the preceding key, allowing adjacent keys to be equal.
The keys [1, 4, 4, 8] are correctly ordered even though the two middle values are the same.

O

Online sorting
Online sorting processes items as they arrive, maintaining an ordered result without needing the entire input in advance.
Insertion sort can extend the sorted prefix after each new record, although insertion may still be linear.

P

Partition
A partition rearranges a range into regions relative to a pivot without requiring that the items inside each region be sorted.
After partitioning around 5, the left region may still contain 3 before 1 and need recursive sorting.
Permutation
A permutation is a rearrangement that preserves all items and the number of times each occurs in the original sequence.
Returning [1, 4] from input [4, 1, 4] loses a copy of 4 and therefore fails preservation.
Pivot
A pivot is a selected key used during partitioning to organize other items into regions according to their order relative to it.
With Lomuto’s final pivot 6, values no larger than 6 move before its eventual fixed position.
Predecessor and successor
A predecessor and successor are the neighboring values just before and at an insertion point when those positions exist.
To find the reading nearest to 43, compare its distances to the values surrounding its insertion point.
Prefix sum
A prefix sum accumulates preceding counts so an output block can start after all records with smaller keys.
Counts [2, 0, 3] give starting positions [0, 2, 2], with an empty middle block sharing the next start.
Preprocessing
Preprocessing performs an initial preparation, such as sorting data, to make later operations cheaper or enable new queries.
The cost of sorting once must be included when comparing repeated binary searches with direct scans.
Primary key
A primary key in a multi-key ordering is the field with the highest sorting priority, determining the main output groups.
Sorting by group first in a tuple key makes each group contiguous before considering its secondary score.
Probe
A probe is one inspection of a selected stored item; its outcome can require more than one comparison operator in code.
A binary-search probe may evaluate equality first and then compare whether the middle value is smaller.

R

Radix base
A radix base specifies the number of possible values of each digit, setting counter-array size and the number of digit passes.
Base 256 handles eight bits per pass, trading 256 counters for fewer passes than a small base needs.
Random access
Random access is the ability to read an item at an arbitrary index directly, without traversing all earlier positions.
An array supports quick middle probes, while a linked list requires walking through links to reach them.
Randomized quicksort
Randomized quicksort chooses pivots using randomness, giving expected logarithmic-depth sorting behavior for distinct keys.
An already sorted distinct-key input cannot force every randomly chosen pivot to be an extreme value.
Recurrence
A recurrence describes a problem’s cost in terms of costs for smaller inputs plus work performed in the current call.
Merge sort’s two half-size calls and linear merge give T(n)=2T(n/2)+Θ(n).
Rightmost insertion point
The rightmost insertion point is the first sorted-array position with a key strictly larger than the target, or the array end.
For [2, 6, 6, 9], the rightmost insertion point of 6 is index 3, just after its two copies.
Run
A run is a consecutive ordered portion of input that an adaptive merge-based sort can reuse as part of its sorting work.
A long ascending stretch of timestamps supplies a run that need not be rebuilt from individual records.

S

Secondary key
A secondary key determines the order among records whose primary keys tie, supplying the next level of sorting priority.
A name field can order equal-score records alphabetically without changing which scores appear first.
Selection sort
Selection sort repeatedly finds the minimum of the unsorted suffix and swaps it into the first remaining output position.
After three passes, the first three positions contain the three smallest input items in order.
Sentinel result
A sentinel result is a special return value that reports a case such as absence instead of identifying a successful result.
A search returning -1 needs a caller check because Python also accepts it as the last list index.
Shift
A shift copies an item to a neighboring slot to open a gap, while the item being inserted is held separately until placement.
Inserting 5 into [2, 7, 9] shifts 9 and 7 right before writing 5 between 2 and 7.
Smaller-side recursion
Smaller-side recursion recurses on the shorter quicksort partition and loops over the larger, bounding nested calls logarithmically.
Even a poor pivot sequence can use a shallow stack, although its repeated scans can remain quadratic.
Sort key
A sort key is the value extracted from an item to determine its position while the complete item moves with it.
When records are sorted by score, each name and timestamp must travel with its associated score.
Stability
Stability is the guarantee that records with equal sort keys remain in the same relative order as they appeared in the input.
A stable customer sort retains time order within each customer when the input was already chronological.
Stable digit pass
A stable digit pass orders records by one digit while retaining their previous relative order whenever that current digit ties.
A hundreds pass must keep 24 before 85 when both have hundreds digit zero and lower digits are already sorted.
Successful-search average
A successful-search average is the expected work over target locations, using a stated probability for each possible position.
If all positions are equally likely, a 19-item linear search averages ten comparisons per successful lookup.
Swap
A swap exchanges the contents of two positions while preserving both items, potentially moving a record across equal keys.
The minimum-selection scan ends with at most one actual swap, even if it updated its minimum many times.

T

Target
A target is the value a search tries to locate, using the equality or ordering rule that defines a match.
Searching a list for order number 318 treats 318 as the target and returns its position if found.
Three-way partitioning
Three-way partitioning groups keys below, equal to, and above a pivot so quicksort can leave its equal-key region out of recursion.
An all-equal array needs a single scan because every item belongs to the completed equal region.
Timsort
Timsort is Python’s stable adaptive merge-based sorting approach, which exploits existing runs and extends short ones before merging.
Already sorted input forms a useful run, allowing Python’s built-in sort to finish in linear time.
Tree height
The height of a comparison decision tree is the longest root-to-leaf path, giving the algorithm’s worst-case comparison count.
A binary tree of height six has at most 64 leaves, too few to distinguish all 120 orders of five keys.
Tuple key
A tuple key orders records by comparing fields from left to right, consulting later fields only when earlier fields tie.
The key (-score, name) orders larger scores first and then sorts equal scores by ascending name.

U

Unsorted suffix
An unsorted suffix is the trailing portion of a partially processed array whose items have not yet reached their final order.
Selection sort’s next minimum search starts at the first position after the finished prefix.

W

Workload
A workload describes the data and operations a program must handle, including lookup frequency, updates, and required output.
A collection searched once and a collection searched thousands of times can justify different preparations.
Worst-case guarantee
A worst-case guarantee bounds the maximum cost over all permitted inputs, supplying a stronger promise than an expected bound.
Merge sort’s time bound can matter when an input source might deliberately choose troublesome key orders.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started