01、二分查找法

二分查找法每次都排查一半的数字,包含则返回其位置,否则返回null。二分查找法的元素列表必须是有序的。
 
 
Python 2 示例:
def binary_search(list, item):
    low = 0
    high = len(list)-1
    
    while low <= high:
        mid = (low + high) / 2
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None


my_list = [1, 3, 5, 7, 9]


binary_search(my_list, 3)

Python 3 示例:

def binary_search(list, item):
    low = 0
    high = len(list)-1
    
    while low <= high:
        mid = int((low + high) / 2)
        guess = list[mid]
        if guess == item:
            return mid
        if guess > item:
            high = mid - 1
        else:
            low = mid + 1
    return None


my_list = [1, 3, 5, 7, 9]


binary_search(my_list, 3)

# 注意:Python 2.x 中x / y 将返回一个整数,因为小数被截断(除法)。但是在 3.x 中x / y 运算符执行“真”除法,结果是FLOAT而不是整数(例如: 1 / 2 = 0.5

Go 示例:

package main


import "fmt"

func binarySearch(list []int, item int) int {

   low := 0
   high := len(list) - 1

   for low <= high {
      mid := (low + high) / 2
      guess := list[mid]
      if guess == item{
         return mid
      }
      if guess > item {
         high = mid - 1
      } else {
         low = mid + 1
      }
   }
   return 0
}

func main() {
   myList := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}

   fmt.Println(binarySearch(myList, 4))

}
原文地址:https://www.cnblogs.com/9527l/p/15349923.html