开始使用免费开始使用

实现二分查找

在本视频中,您学习了如何实现线性查找二分查找,并了解了它们之间的差异。

在本练习中,您需要实现 binary_search() 函数。您能完成吗?

本练习是课程的一部分

Python 中的数据结构与算法

查看课程

练习说明

  • 检查查找值是否等于中间位置的值。
  • 检查查找值是否小于中间位置的值。
  • last 设为 middle 减去 1。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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