二分查找及线性查找的效率对比及代码

基于线性查找:  时间复杂度为O(n)

l=list(range(200000000))
def linearserch(l,aim):
    for index,val in enumerate(l):
        if aim == val:
            return index
    else:
        return "没有您要的查找的值"
linearserch(l,9999999)

 

基于二分查找:O(log(n)/log2n)

l=list(range(200000000))
def Binary_search(l,aim):
    left=0
    right=len(l)-1
    while left <=right:
        mid = (left + right) // 2
        val = l[mid]
        if aim < val:
            right = mid-1
        elif aim > val:
            left = mid +1
        else:
            return mid
    else:
        return None
Binary_search(l,9999999)

 

 

两者之间效率对比:

import time

def timer(func):
    def inner(l,aim):
        start = time.time()
        ret =func(l,aim)
        print(time.time()-start)
        return ret
    return inner

l=list(range(200000000))
@timer
def linearserch(l,aim):
    for index,val in enumerate(l):
        if aim == val:
            return index
    else:
        return "没有您要的查找的值"
linearserch(l,9999999)

@timer
def Binary_search(l,aim):
    left=0
    right=len(l)-1
    while left <=right:
        mid = (left + right) // 2
        val = l[mid]
        if aim < val:
            right = mid-1
        elif aim > val:
            left = mid +1
        else:
            return mid
    else:
        return None
Binary_search(l,9999999)

 

posted @ 2019-07-06 01:37  小萍瓶盖儿  阅读(365)  评论(0编辑  收藏  举报