Retrieve linear search
Describe the first-match algorithm. How many comparisons might it need for an absent target in a list of 1,000 values?
Use sorted data to rule out half of the remaining candidates at each step.
Start with all eight values. Check the middle index, rounding down.
low = 0mid = —high = 7Highlight = the line just executed. Skipped branches stay unhighlighted.
def binary_search(items, target): low = 0 high = len(items) - 1 while low <= high: mid = (low + high) // 2 if items[mid] == target: return mid elif items[mid] < target: low = mid + 1 else: high = mid - 1 return -1 Ready to call binary_search(items, 42).
Describe the first-match algorithm. How many comparisons might it need for an absent target in a list of 1,000 values?
Search [3, 8, 12, 17, 23, 31, 42, 56] for 31 by hand. Use zero-based indices, low = 0, high = len(items) - 1 and mid = (low + high) // 2. After a failed comparison, explain which half can be discarded.
Build a table with iteration, low, high, mid, items[mid] and next action. Trace a successful search for 31 and an unsuccessful search for 20. Record why the loop stops in each case.
Write binary_search(items, target), returning a matching index or -1. Continue while low <= high. Test an empty list, a singleton, first and last values, and an absent value. Compare expected and actual results.
Explain why the next boundary is mid + 1 or mid - 1, rather than mid. State what you can guarantee if duplicate values occur.
What makes the search interval shrink, and why would unsorted input break the reasoning?
Complete Problems 1 and 2 in the algorithms handout, then read the textbook’s binary-search section. Have your work ready for Monday, 21 September.