Back to Freecodecamp

Step 4

curriculum/challenges/english/blocks/workshop-binary-search/683ec95f2f8781355556ff7c.md

latest1.2 KB
Original Source

--description--

Now that you've defined the boundaries of your search, it's time to create the loop that will perform the binary search algorithm.

Binary search works by repeatedly narrowing down the search space. This process continues as long as there is a valid range of elements to check.

You can express this with a while loop that will continue as long as your low pointer is less than or equal to your high pointer.

If low ever becomes greater than high, it means the search space has become empty, and the value is not in the list.

Inside the binary_search function, create a while loop with a condition that checks if low is less than or equal to high. Inside the loop, add the pass keyword as a placeholder for now.

--hints--

You should create a while loop that runs while low is less than or equal to high.

js
({ test: () => runPython(`
_cond = _Node(_code).find_function("binary_search").find_whiles()[0].find_conditions()[0]
assert _cond.is_equivalent("low <= high") or _cond.is_equivalent("high >= low")`
) })

--seed--

--seed-contents--

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