• 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))
    
    }
  • 相关阅读:
    eureka 注册中心(单机版)
    金蝶实际成本培训01
    查看WIN10内核
    金蝶K3 WISE 15.0 GUID
    win10卸载系统自带office365
    金蝶K3wise15.0BOM维护默认只能查看登录账户作为建立人的BOM清单
    阿里云邮箱代收邮件
    金蝶寄售业务流程
    转-商品流通企业代销商品核算方法
    转-ERP待检仓、代管仓、赠品仓
  • 原文地址:https://www.cnblogs.com/9527l/p/15349923.html
Copyright © 2020-2023  润新知