Back to Freecodecamp

Step 13

curriculum/challenges/english/blocks/workshop-binary-search/684165a72e33e26a40904f8b.md

latest1.2 KB
Original Source

--description--

Finally, if the value is not found at the middle and is also not greater than value_at_middle, then the value must be less than value_at_middle, and must be on the left. The else block will handle this.

So, finish up the loop by removing the break keyword and adding an else block. Inside it, update the high variable by subtracting 1 from mid.

--hints--

You should replace the break keyword with an else block that updates the high variable to mid - 1.

js
({ test: () => runPython(`
_Node(_code).find_function("binary_search").find_whiles()[0].find_ifs()[0].find_bodies()[2].is_equivalent("high = mid - 1")
`) })

--seed--

--seed-contents--

py
def binary_search(search_list, value):
    path_to_target = []
    low = 0
    high = len(search_list) - 1

    while low <= high:
        mid = (low + high) // 2
        value_at_middle = search_list[mid]
        path_to_target.append(value_at_middle)

        if value == value_at_middle:
            return path_to_target
        elif value > value_at_middle:
            low = mid + 1
--fcc-editable-region--
        break
--fcc-editable-region--
    return []
    
print(binary_search([1, 2, 3, 4, 5], 3))
print(binary_search([1, 2, 3, 4, 5, 9], 4))