Python 二分查找

递归方式:

array = [3,5,8,12,15,17,40,54,65,80]

def binary_search_v1(start,end,array,target):

    if start > end:
        return

    middle = int((start+end)/2)
    middle_element = array[middle]

    if target == middle_element:
        print('got it {},index is {}'.format(middle_element,middle))
        return middle
    
    elif target>middle_element:
        return binary_search_v1(middle+1,end,array,target)
    else:
        return binary_search_v1(start,middle-1,array,target)
   

for i in array:
    binary_search_v1(0,len(array),array,i)

非递归方式:

array = [3,5,8,12,15,17,40,54,65,80]

def binary_search_v2(start,end,array,target):

    while True:

        if start>end:
            break
        
        middle = int((start+end)/2)
        middle_element = array[middle]

        if target == middle_element:
            print('got it {},index is {}'.format(middle_element,middle))
            return middle
        
        elif target > middle_element:
            start = middle+1
        else:
            end = middle-1 

for i in array:
    binary_search_v2(0,len(array),array,i)
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页