开始使用免费开始使用

使用递归的二分查找

在本练习中,您将用递归实现刚学到的二分查找算法。请回忆:递归函数是指函数调用自身。

本练习是课程的一部分

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))
编辑并运行代码