zoukankan      html  css  js  c++  java
  • 二分查找

    二分查找要求数组必须有序,代码比较容易理解

    如下:

    # coding: utf-8
    
    # non-recurse
    # 迭代版
    def binary_search(alist, aitem):
        n = len(alist)
        start = 0
        end = n - 1
        while start <= end:
            mid = (start + end) // 2
            if alist[mid] == aitem:
                return True
            elif aitem < alist[mid]:
                end = mid - 1
            else:
                start = mid + 1
        return False
    
    
    # recurse
    # 递归版
    def binary_search_recurse(alist, aitem):
        n = len(alist)
        if n == 0:
            return False
        mid = n // 2
        if aitem == alist[mid]:
            return True
        elif aitem < alist[mid]:
            return binary_search_recurse(alist[:mid], aitem)
        else:
            return binary_search_recurse(alist[mid + 1:], aitem)
    
    if __name__ == "__main__":
        arr1 = [0, 1, 3, 5, 7, 8]
        item = 3
        print 
        print(binary_search(arr1, item))
        # print(binary_search_recurse(arr1, item))
    
  • 相关阅读:
    ES6 一些新特性的总结
    前端模块化开发的规范:AMD与CDM
    webpack与grunt/glub 的比较
    前端总结(一)
    前端性能的优化
    Typescript 常见写法
    显示模式------行内元素、块元素,行内块元素
    浏览器前缀及内核
    BFC规范
    数据库习题练习
  • 原文地址:https://www.cnblogs.com/becker/p/8232493.html
Copyright © 2011-2022 走看看