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.
Spend about 3 minutes on each during practice time. Predict, run, change one thing, then explain. These prompts do not add homework.
A starter is runnable code to explore or complete. If the playground restores your saved code, the linked starter is selected in Example: use Load example when ready. Download your work before confirming replacement.
Compute the middle index, then discard the lower half. Print the new interval.
No imports needed.
// is integer floor division. This update is valid only when the target is greater than values[mid] in sorted data.
# // is integer floor division.
values = [3, 8, 12, 17, 23, 31]
low, high = 0, len(values) - 1
mid = (low + high) // 2
print(mid, values[mid])
low = mid + 1
print(low, high)
Trace how often a candidate count can be halved before it reaches zero. Compare 8 and 16.
No imports needed.
This is a growth model, not a complete binary-search implementation.
# This is a growth model, not a complete binary-search implementation.
remaining = 8
steps = 0
while remaining > 0:
remaining //= 2
steps += 1
print(steps)
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.