始める無料で始める

再帰を使った二分探索

この演習では、学んだばかりの二分探索(binary search)再帰で実装します。再帰関数とは、自分自身を呼び出す関数のことでしたね。

この演習はコースの一部です

Pythonで学ぶデータ構造とアルゴリズム

コースを見る

演習の手順

  • ベースケースを定義します。
  • 探索値が中央の値と等しいかを確認します。
  • リストの左半分に対して binary_search_recursive() 関数を再帰的に呼び出します。
  • リストの右半分に対して binary_search_recursive() 関数を再帰的に呼び出します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

def binary_search_recursive(ordered_list, search_value):
  # Define the base case
  if ____(ordered_list) == 0:
    return False
  else:
    middle = len(ordered_list)//2
    # Check whether the search value equals the value in the middle
    if search_value == ____:
        return True
    elif search_value < ordered_list[middle]:
        # Call recursively with the left half of the list
        return ____(ordered_list[:middle], search_value)
    else:
        # Call recursively with the right half of the list
        return ____
  
print(binary_search_recursive([1,5,8,9,15,20,70,72], 5))
コードを編集して実行