Editor

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 lesson

Write 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:

  • Start with low = 0, high = len(items) - 1 and a count of 0.
  • While low <= high: set mid = (low + high) // 2 and add 1 to the count.
  • If items[mid] equals the target, return the count.
  • If the target is smaller than items[mid], set high = mid - 1; otherwise set low = mid + 1.
  • When the loop ends, return the count.
  • binary_search_checks([3, 8, 12, 17, 21, 26, 30], 17)  ->  1
    binary_search_checks([3, 8, 12, 17, 21, 26, 30], 26)  ->  2
    def 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.

    RunsExpected 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

    All Python exercises · 50 practice problems