Back to Freecodecamp

Step 14

curriculum/challenges/english/blocks/workshop-binary-search/684169b00a073c9b9f0a703c.md

latest1.5 KB
Original Source

--description--

Did you notice the second function call now has the values 3, 5, 4 in the list? That indicates the binary search is working as intended.

This is how it happened: The algorithm first checked 3 as the middle of the initial list. Since 4 is greater than 3, the search shifted to the right half. It then examined 5 as the new middle. Because 4 is less than 5, the search moved to the left, ultimately identifying 4 as the middle of the final range.

To test the function again, call it with [1, 3, 5, 9, 14, 22], 10 and print the call right away. This is a situation in which the value will not be found.

--hints--

You should call the function with binary_search([1, 3, 5, 9, 14, 22], 10) and print it right away.

js
({
    test: () => assert(runPython(
        `_Node(_code).has_call("print(binary_search([1, 3, 5, 9, 14, 22], 10))")`
      )
    )
})

--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
        else:
            high = mid - 1

    return []
    
print(binary_search([1, 2, 3, 4, 5], 3))
print(binary_search([1, 2, 3, 4, 5, 9], 4))
--fcc-editable-region--

--fcc-editable-region--