- Learn
- Computer Science & IT
- Programming
- Data Structures and Algorithms
- Sorting and Searching
Sorting and Searching
IntermediateLesson 4 of 10 in Data Structures and Algorithms Course
What you will learn
- 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 searchDefine 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 searchWrite, 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 thresholdsUse 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.
- Search any sequence with linear search
- 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 comparedDefine sorting, keys and comparison sorts, and judge an algorithm by its comparisons, data moves, extra memory, adaptivity and correctness.
- Sort by repeated selectionImplement and trace selection sort, count its comparisons and swaps, and explain why it is not stable.
- Sort by repeated insertionImplement 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 keysDefine a stable sort, identify which algorithms are stable, and use stability to sort records by more than one key.
- Describe the sorting problem and how sorts are compared
- 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 sortWrite 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 quicksortImplement quicksort with Lomuto partitioning, trace a partition by hand, and recognize Hoare partitioning and quicksort's instability.
- Analyze quicksort and choose pivots wellDerive quicksort's best, worst and expected costs, and use random pivots, three-way partitioning and smaller-side recursion to make it fast and safe.
- Sort by splitting and merging with merge sort
- 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 sortingModel 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 sortImplement 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 sortRun LSD radix sort with a stable digit sort, explain why stability makes it correct, and choose a base to balance passes and memory.
- Prove the n log n lower bound for comparison sorting
- 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 propertiesSummarize 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 taskMatch the method to the data and the requirements, decide when sorting before searching pays off, and justify the choice with costs.
- Compare the algorithms by cost and properties
Sorting and Searching study guide
1Find 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 , the best case takes one comparison, when the target is first. The worst case takes comparisons, when it is last or absent. If a successful target is equally likely to occupy any position, the average is
Thus worst-case and uniformly distributed successful-search time are . The index and target use 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 targets and each uses membership on an -item list, the total is , reaching when searches reach the end. If each matches the first item, it is only . 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 and extra memory is .
- 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:
- Bounds 0 through 9 give
mid = 4. Value 34 is too small, solo = 5. - Bounds 5 through 9 give
mid = 7. Value 66 is too large, sohi = 6. - Bounds 5 through 6 give
mid = 5. Value 42 is too small, solo = 6. - 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 , the maximum number of middle-element probes is : 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 and the best case is . An empty array takes zero probes.
The loop needs extra memory. A recursive implementation passes the original array plus bounds, using 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 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 <= hiand updates that excludemid. - For nonempty input, at most 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 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 comparisons, but shifting the list for insertion still takes 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.
bisectsearches with a key value;insortinserts a complete item.
2Sort 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 distinct values gives . 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]:
- Scan all five items. The minimum is 10 at index 1. Swap with index 0:
[10, 29, 14, 37, 13]. - Scan the suffix beginning at index 1. Its minimum is 13. Swap it with 29:
[10, 13, 14, 37, 29]. - The next suffix has minimum 14, already at index 2. Leave it there.
- 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 items, the exact comparison count is
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 . It is not adaptive.
There are at most actual swaps and only 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 , 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 key comparisons.
- The guarded implementation uses at most 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]:
- Insert 3 by shifting 7:
[3, 7, 5, 1, 9, 2]. - Insert 5 by shifting 7:
[3, 5, 7, 1, 9, 2]. - Insert 1 by shifting 7, 5, and 3:
[1, 3, 5, 7, 9, 2]. - Insert 9 with no shift.
- 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 . Including the outer loop, running time is .
A sorted nonempty list has zero shifts and value comparisons: time. A reversed list of distinct keys has shifts and value comparisons: time. Randomly ordered distinct keys also give quadratic average time, with roughly comparisons.
When each item's displacement from its final position is at most a small , insertion sort costs . Including the 1 keeps the bound meaningful even when . 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 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 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 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.
3Sort 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 and , at most comparisons are needed. Copying the whole output costs 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
At each level, merging handles a total of items. There are about levels, so plain merge sort takes time on sorted, reversed, and random inputs. For one million items, is about 20 million; a quadratic sort's roughly 500 billion comparisons are about 25,000 times as many.
Array merging needs extra storage, plus a logarithmic recursion stack. Python slices add copying at each level but keep this implementation's overall time at . 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 . 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 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 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 items, that means pivot comparisons. The total cost depends on how much the recursive ranges shrink.
Compare the recursion shapes
When pivots split ranges near the middle,
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:
The comparison count becomes , 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 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 , where . For large inputs it is about , 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 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 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 worst case, array merge sort offers those properties at the cost of an auxiliary array.
Key Takeaways
- Proportional splits give logarithmic depth and 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.
4Know 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 possible relative orders of 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 leaves. A binary tree of height has at most leaves, so
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 , at least half the factors in are at least . Thus
The same asymptotic conclusion holds for odd sizes by rounding the half-size terms. A more precise estimate is . 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 million.
Merge sort's worst-case 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 when distinct-key input orders are equally likely. Randomization cannot eliminate that average information requirement. Randomized quicksort remains within a constant factor, with about expected comparisons for large distinct-key inputs.
Already sorted input can still take only 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 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 leaves.
- The worst-case comparison count is at least .
- 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 items; initialization and prefix sums scan counters. Time and extra memory are both for this stable array version. When , 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 , 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.
- Stable sort by ones digit:
[170, 90, 802, 2, 24, 45, 75, 66]. - Stable sort that result by tens digit:
[802, 2, 24, 45, 66, 170, 75, 90]. - 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 passes, keys are ordered by their last 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 digits and base , each pass costs , giving time and extra memory reused across passes. For positive maximum , the digit count is ; 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 for a fixed positive integer and the base is , at most 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 digits in base , time is and extra memory is .
- A larger base reduces passes while increasing counter storage.
- Fixed-length strings can use character passes; MSD recursively sorts prefix groups.
5Compare 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 is the item count, the integer-key range size, the digit count, and the radix base. The sorting memory column gives extra storage beyond the input.
| Method | Time | Extra memory | Stable in the form taught? |
|---|---|---|---|
| Selection | in all cases | No | |
| Insertion | Best ; worst/average | Yes | |
| Plain array merge | in all cases | Yes | |
| Randomized quicksort | Expected ; worst | stack with smaller-side recursion | No |
| Stable counting | Yes | ||
| LSD radix | 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 . Ordinary two-call recursion can need a linear stack in a bad case.
For searches, linear search works on unsorted sequences in worst-case time. Iterative binary search takes 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 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 . 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: time with . Plain selection sort or quicksort could scramble ties.
If worst-case time must be bounded for potentially hostile input, merge sort guarantees . 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 with , where is the lookup count, the average linear-search cost, the one-time sort cost, and 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 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
1From a scan to a search boundary
16 steps
- 1IntroductionChoose 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.
- 2ExampleScan until the first match
Search
[42, 17, 8, 99, 23]for99.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.
- 3Key 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 comparisons.
If a successful target is equally likely to occupy each position, average the costs 1 through to get . The uniform-position assumption matters: a frequently requested value near the front can make an actual workload much cheaper.
- 4ChallengePlace the failure return
A scan of
[14, 29, 6, 38]returns-1immediately when its first item differs from target38. Where should that return go, and what should a corrected search return?---reveal---
Put
return -1after 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. - 5ExplanationKeep all possible matches inside the bounds
For inclusive binary search, begin with
lo = 0andhi = 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.
- 6ExampleMake the first middle probe
Use
[3, 8, 15, 21, 34, 42, 57, 66, 79, 91], target57, 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 sethi = 6. The remaining range has only indexes 5 and 6. - 7ExampleFinish with a one-item range
Bounds 5 through 6 give middle index 5, value 42. Move
loto 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. Usingwhile lo < hihere would stop just before the successful final probe. - 8TipSeparate 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.
- 9ChallengeTrace an absent target
Inclusive binary search uses lower middles on
[5, 13, 18, 26, 35], looking for20. 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 = 3andhi = 2. The candidate range is empty, so return failure. A final insertion point of 3 would lie between 18 and 26. - 10ExplanationKeep 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 withhi = len(a).If
a[mid] < x, movelopastmid. Otherwise movehitomid, keeping equality on the boundary’s right side. At termination, everything before the returned position is smaller, and everything from it onward is at leastx. - 11ExampleUse 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.
- 12ChallengeCount 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.
- 13ExampleInspect 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.
- 14ConnectionSearch a monotone test
You can halve a domain even when no array is stored. For nonnegative integers, the test
x * x >= 200is 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.
- 15ChallengeCombine 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.
- 16RecapCheck 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.
2Build and preserve a sorted prefix
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrack records as well as keys
- 2ExplanationCheck two obligations
- 3ChallengeTest a plausible-looking result
- 4ExplanationFind a minimum before moving it
- 5ExampleComplete the first selection passes
- 6Key InsightFew swaps do not mean few comparisons
- 7ChallengePredict the next fixed position
- 8ExplanationSave the next item before shifting
- 9ExampleInsert one item, then the next
- 10ExampleFollow the longer insertion
- 11Key InsightMeasure the disorder removed
- 12ChallengeCount shifts from the input
- 13ExplanationMake equal keys visibly different
- 14ExampleEstablish a secondary order first
- 15ChallengeChoose the order of stable passes
- 16ConnectionSupply a tie breaker explicitly
- 17ChallengePreserve a useful existing order
- 18RecapInspect the invariant and the ties
3Merge halves and partition around pivots
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionPut the main work on either side of recursion
- 2ExplanationConsume the smaller front item
- 3ExampleBegin a merge
- 4ExampleCopy the remaining tail
- 5Key InsightCount work across each level
- 6ChallengeMerge and preserve the tail
- 7ExplanationGrow a pivot-relative region
- 8ExampleMove small keys across the boundary
- 9ExampleFix the pivot and leave the sides
- 10TipCheck what a partition returns
- 11ChallengePartition without overclaiming
- 12ExplanationRead the recursion shape
- 13ConnectionRandomness changes the expectation
- 14Key InsightRemove equal keys from recursion
- 15ChallengeSeparate stack space from running time
- 16ChallengeSelect a guarantee the task needs
- 17RecapInspect the remaining subproblems
4Use the comparison limit and integer structure
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk what information the method reads
- 2ExplanationMake comparisons into branches
- 3ExampleTurn leaves into a depth bound
- 4Key InsightKeep the model and case attached
- 5ChallengeTest a claimed comparison bound
- 6ExplanationTurn frequencies into block starts
- 7ExamplePlace records in their encounter order
- 8TipInclude unused key values in the cost
- 9ChallengeCompute an offset and starts
- 10ExplanationBuild order from the least significant digit
- 11ExampleComplete the first digit pass
- 12ExampleKeep earlier order inside the next ties
- 13ChallengeApply two stable passes
- 14ConnectionTrade counter space for fewer passes
- 15ChallengeUse key structure to change the bound
- 16RecapCheck what makes the speed possible
5Choose for a complete workload
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionChoose the operation before the algorithm
- 2ExampleCompare input order under one size
- 3ConnectionGive existing order a role
- 4ChallengeDistinguish growth from a small-input timing
- 5ExplanationAccount for the sort before the searches
- 6ExampleEstimate a repeated-lookup workload
- 7ChallengeCompare both complete plans
- 8ExampleLet stability decide a record sort
- 9TipInclude maintenance and memory
- 10ChallengeWrite a complete justification
- 11RecapMake the decision reviewable
Sorting and Searching practice questions
Set 1: Trace searches and sorting steps10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
[5, 2, 4], how many inversions are present?Show answerHide answer
Question 4 of 10
80*n basic operations; method B takes n*n. At n = 16, which uses fewer operations, and which has better growth for large n?Show answerHide answer
Question 5 of 10
-6 through 9 by offset counting sort?Show answerHide answer
Question 6 of 10
0..n-1. Why is this compatible with the comparison-sorting lower bound?Show answerHide answer
Question 7 of 10
[(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?Show answerHide answer
Question 8 of 10
[1, 6, 12] and [3, 8] make?Show answerHide answer
Question 9 of 10
bisect.insort. What is the worst-case time for the whole insertion?Show answerHide answer
Question 10 of 10
[8, 3, 7, 2, 6, 5], excluding each fixed pivot from recursive calls. How many pivot comparisons does the complete sort make?Show answerHide answer
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
lo = 0, hi = 6, and target 25 in [4, 10, 16, 22, 28, 34, 40]. What bounds remain after its first unsuccessful probe?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
items.sort() after sorting the list successfully?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
[(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?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
[5, 8, 8, 12, 16, 16, 19, 23], how many values lie in the closed range from 8 through 16?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
[24, 6, 19, 3, 12]?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
a = [2, 4, 4, 4, 9, 11], what are bisect_left(a, 4) and bisect_right(a, 4)?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
BAA, ABA, AAB, BBA. Stable LSD radix passes use alphabetic character order. What order follows the first two passes, before the leading-character pass?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
[8, 3, 8, 1] produces [1, 3, 8]. What correctness requirement has failed?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
[42, 17, 31, 12, 27]?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
[2, 9, 14, 20, 27, 33, 46, 58] for 33. What sequence of middle values does it inspect?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
5 into the sorted prefix of [2, 7, 10, 5, 13]. What is the array after that insertion?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
lo..p and p+1..hi. What occurs on [3, 5, 7], and what change repairs it?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
[4, 1, 3, 2]?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
[7, 2, 6, 3, 5]?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
[2, 0, 2, 1, 3, 1] in range 0..3. What initial starting positions should its stable output blocks use?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
-1. It searches [26, 9, 14] for 8, then the caller immediately prints a[result]. What happens?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
[("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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
while lo < hi and otherwise the usual bounds and updates. It searches [6, 15, 24] for 24. What happens?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
[18, 7, 31, 12, 7] from the front. What index does it return for target 7?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
[4, 1, 3, 2], how many key comparisons and intervening-item shifts occur, excluding minimum-placement writes?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
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")]?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
[(2, "a"), (0, "b"), (2, "c"), (0, "d")] left to right. What output does this produce?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Adaptive sort
Asymptotic optimality
B
Binary search
Bottom-up merge sort
Break-even point
C
Candidate range
Closed interval
Comparison lower bound
Comparison sort
Constant factor
Counting sort
D
Decision tree
Digit extraction
(x // 100) % 10 extracts the hundreds digit without comparing x with another key.Divide and conquer
E
Expected running time
H
Half-open range
[0, n) and return n without ever reading the nonexistent item at n.Hoare partitioning
Hybrid sort
I
In-place sort
Inclusive bounds
lo == hi because the last candidate has not yet been ruled out.Insertion sort
Inversion
[4, 1, 3], the pairs (4, 1) and (4, 3) account for the two shifts needed by insertion sort.K
Key offset
Key range size
L
Leftmost insertion point
[2, 6, 6, 9], the leftmost insertion point of 6 is index 1, just before the equal block.Linear search
Lomuto partitioning
Loop invariant
LSD radix sort
M
Median-of-three
Merge
Merge sort
Monotone condition
MSD radix sort
N
Nondecreasing order
[1, 4, 4, 8] are correctly ordered even though the two middle values are the same.O
Online sorting
P
Partition
Permutation
[1, 4] from input [4, 1, 4] loses a copy of 4 and therefore fails preservation.Pivot
Predecessor and successor
Prefix sum
Preprocessing
Primary key
Probe
R
Radix base
Random access
Randomized quicksort
Recurrence
Rightmost insertion point
[2, 6, 6, 9], the rightmost insertion point of 6 is index 3, just after its two copies.Run
S
Secondary key
Selection sort
Sentinel result
-1 needs a caller check because Python also accepts it as the last list index.Shift
[2, 7, 9] shifts 9 and 7 right before writing 5 between 2 and 7.Smaller-side recursion
Sort key
Stability
Stable digit pass
Successful-search average
Swap
T
Target
Three-way partitioning
Timsort
Tree height
Tuple key
(-score, name) orders larger scores first and then sorts equal scores by ascending name.U
Unsorted suffix
W
Workload
Worst-case guarantee
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.