利用Python写的二分法查找算法及测试

来源:互联网 发布:淘宝 云客服 工资 编辑:程序博客网 时间:2024/04/30 10:20

2011-05-21

#二分法查找  版本 Python 3.1
lis
=list(range(11))  #用于存放查找的数据(1~6)
print(lis)
lenth=len(lis)
half=int(lenth/2)

def halfSearch(num):
    isFound = False
    for i in range(half+1):
        if num in lis[:half+1]:  #在[0,half]中查找.
           
print('num %f Already found in front part!/n',num)
            isFound = True
            break
        elif not isFound:        #若未找到,则在[half+1,结尾]查找.
            for i in range(half+1,lenth+1):
                if num in lis[half+1:]:
                    print('num %f Already found in back part!/n' % num)
                    isFound = True
                    break
    if not isFound:
        print('num %f not found!/n' % num)
 

        

def testhalfSearch(num):
    print('Found %f consistence :' % num)
    halfSearch(num)


print('test the half Search:/n中二分查找测试')
testhalfSearch(10)

原创粉丝点击