二分查找 python实现

传统的顺序查找就是一个一个的比,时间复杂度为O(n)
二分查找是很基本的查找方式,前提是待查找的列表是有序的,所以每次都跟中间的那个数比较。
但是如果数据较大,二分查找不一定好用,因为需要先排序,有可能排序需要的成本更高。

下面是二分查找的python实现方法。

def binarySearch(alist, item):
    first = 0
    last = len(alist) - 1
    found = False

    while not found and last >= first:
        mid = (last + first) // 2
        if item == alist[mid]:
            found = True
        else:
            if item > alist[mid]:
                first = mid + 1
            else:
                last = mid - 1
    return found

递归版本

def binarySearchRecursive(alist, item):
    if len(alist) == 0:
        return False

    else:
        mid = len(alist) // 2
        if alist[mid] == item:
            return True
        else:
            if item > alist[mid]:
                return binarySearchRecursive(alist[mid + 1:], item)
            else:
                return binarySearchRecursive(alist[:mid], item)

测试:

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binarySearch(testlist, 5))
print(binarySearch(testlist, 17))
#输出
#False
#True

分析时间复杂度:
如果长度为n,那么第一次查找后,留下了2/n项,第二次查找后,留下了 2 / n 2 项…所以第i次查找后剩下了 2 / n i
要得到最后一项查找共用了多少次,令 1 = 2 / n i :
i = l o g 2 n 所以时间复杂度为 l o g 2 n

猜你喜欢

转载自blog.csdn.net/lisa_ren_123/article/details/80862796