zoukankan      html  css  js  c++  java
  • 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))
    
    }
  • 相关阅读:
    Python函数高级
    Python 2和3的区别
    GIL,python全局解释器锁
    Python中的 list
    python中的单例
    新式类和经典类
    整理的排序算法
    Python的双下划方法
    Python 中闭包函数和装饰器
    面向对象,特性之继承
  • 原文地址:https://www.cnblogs.com/9527l/p/15349923.html
Copyright © 2011-2022 走看看