算法-二分查找-python实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/imilano/article/details/79326297
#coding=utf-8
import random

'''
采用数组的方式实现binary_search
数组元素必须有序排列

时间复杂度为对数级别(2为底)
'''

def binary_search(list,item):
    if len(list):
        low=0
        high=len(list)-1

        while low <= high:
            mid=int((low+high)/2)
            guess=list[mid]

            if guess > item:
                high=mid-1
            if guess < item:
                low=mid+1
            if guess == item:
                return mid
    else:
        return None

# 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:
#             high=mid-1
#         if guess < item:
#             low=mid+1
#         if guess == item:
#             return mid 
#     return None

#测试代码

my_list=[x for x in range(0,100)]
find=0
notfind=0
for x in range(0,100):
    item=random.randint(0,100)
    mid=binary_search(my_list,item)
    if not mid:
        notfind=notfind+1
    else:
        find=find+1
        print("item:%d,index:%d" %(item,mid))

print("*************我是分割线**************")
print("Match %d times \t don't match %d times " %(find,notfind))


猜你喜欢

转载自blog.csdn.net/imilano/article/details/79326297