二分查找

二分查找,就是对于已排好序的序列,查找某个值,每次都对比中间值,比中间值小,就去序列前面找,否则就去后面找,知道找到为止,否则返回-1。

这里分递归和非递归两种方式组成,其中非递归方式调用的适合更符合日常习惯。

ll=[1,3,5,7,9,11,13,15]
#递归方式
def Binary_search(L,value,left,right):
    if right>=left:
        mid=(left+right)//2
        if value==L[mid]:
            return mid
        elif value>mid:
            return Binary_search(L,value,mid+1,right)
        else:
            return Binary_search(L,value,left,mid-1)
    else:
        return -1
#非递归方式
def Binary_search2(L,value):
    left=0
    right=len(L)-1
    while right>=left:
        mid=(left+right)//2
        if value==L[mid]:
            return mid
        elif value>L[mid]:
            left=mid+1
        else:
            right=mid-1
    return -1
    
#result=Binary_search(ll,11,0,len(ll)-1)
result=Binary_search2(ll,15)
if result!=-1:
    print('The index of the value is {}'.format(result))
else:
    print('I can not find the value in ll')
ll=[1,3,5,7,9,11,13,15]
#
def Binary_search(L,value,left,right):
    if right>=left:
        mid=(left+right)//2
        if value==L[mid]:
            return mid
        elif value>mid:
            return Binary_search(L,value,mid+1,right)
        else:
            return Binary_search(L,value,left,mid-1)
    else:
        return -1
#
def Binary_search2(L,value):
    left=0
    right=len(L)-1
    while right>=left:
        mid=(left+right)//2
        if value==L[mid]:
            return mid
        elif value>L[mid]:
            left=mid+1
        else:
            right=mid-1
    return -1
    
#result=Binary_search(ll,11,0,len(ll)-1)
result=Binary_search2(ll,15)
if result!=-1:
    print('The index of the value is {}'.format(result))
else:
    print('I can not find the value in ll')
原文地址:https://www.cnblogs.com/xiaoxiong-kankan/p/12911655.html