Aan de slagGa gratis aan de slag

Implementing binary search

In this video, you learned how to implement linear search and binary search and saw the differences between them.

In this exercise, you need to implement the binary_search() function. Can you do it?

Deze oefening maakt deel uit van de cursus

Data Structures and Algorithms in Python

Cursus bekijken

Oefeninstructies

  • Check whether the search value equals the value in the middle.
  • Check whether the search value is smaller than the value in the middle
  • Set last to the value of middle minus one.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

def binary_search(ordered_list, search_value):
  first = 0
  last = len(ordered_list) - 1
  
  while first <= last:
    middle = (first + last)//2
    # Check whether the search value equals the value in the middle
    if ____ == ____:
      return True
    # Check whether the search value is smaller than the value in the middle
    elif ____ < ____:
      # Set last to the value of middle minus one
      ____
    else:
      first = middle + 1
  return False
  
print(binary_search([1,5,8,9,15,20,70,72], 5))
Code bewerken en uitvoeren