Count the Binary Search Checks
Advanced · Write the code · from Linear Search and Binary Search: Counting the Checks
From the lesson: Linear Search and Binary Search: Counting the Checks
Searching a list means checking elements until you find the one you want, and the method you choose decides whether that takes 3 checks or 3 million. Linear search works on any list. Binary search is far faster on big lists, but it only works when the data is sorted.
Read the lessonWrite binary_search_checks(items, target) for a sorted list. It returns how many elements binary search examines before it finds target or runs out of elements. Follow these steps exactly:
low = 0, high = len(items) - 1 and a count of 0.low <= high: set mid = (low + high) // 2 and add 1 to the count.items[mid] equals the target, return the count.items[mid], set high = mid - 1; otherwise set low = mid + 1.binary_search_checks([3, 8, 12, 17, 21, 26, 30], 17) -> 1
binary_search_checks([3, 8, 12, 17, 21, 26, 30], 26) -> 2def binary_search_checks(items, target):
# Follow the steps in the instructions
pass
What Check runs
Your code runs first, then each of these lines, and 2 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| binary_search_checks([3, 8, 12, 17, 21, 26, 30], 17) | 1 |
| binary_search_checks([3, 8, 12, 17, 21, 26, 30], 26) | 2 |
| binary_search_checks([3, 8, 12, 17, 21, 26, 30], 4) | 3 |
More Linear and Binary Search exercises
- Fix the Early ExitBeginner
- Most Checks for Binary SearchIntermediate