二分查找

  • Post author:
  • Post category:其他

一、二分查找(Binary Search)

1.1 二分查找的前提:

  1. 目标函数单调性(单调递增或者递减)(Monotonic Increasing and Decreasing)
  2. 存在上下界(Bounded)
  3. 能够通过索引访问(Index Accessible)
left, right = 0, len(array) - 1
while left <= right:
  mid = (left + right) / 2
  if array[mid] == target:
  # find the target!!
  break or return result
  elif array[mid] < target:
  left = mid + 1
  else:
  right = mid - 1

1.2 示例:

在递增数组里[10, 14, 19, 26, 27, 31, 33, 35, 42, 44]查找:31
在这里插入图片描述


版权声明:本文为weixin_39030846原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。