ComeçarComece gratuitamente

Implementação da pesquisa binária

Neste vídeo, você aprendeu a implementar a pesquisa linear e a pesquisa binária e viu as diferenças entre elas.

Neste exercício, você precisa implementar a função binary_search(). Você consegue fazer isso?

Este exercício faz parte do curso

Estruturas de dados e algoritmos em Python

Ver Curso

Instruções de exercício

  • Verifique se o valor da pesquisa é igual ao valor no meio.
  • Verifique se o valor da pesquisa é menor do que o valor no meio
  • Defina last como o valor de middle menos um.

Exercício interativo prático

Experimente este exercício preenchendo este código de exemplo.

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))
Editar e executar código