Python binary search code implementation

Binary search

Binary search is a search algorithm that finds a specific element in an ordered array . The search process starts from the middle element of the array. If the middle element happens to be the element to be searched, the search process ends; if a particular element is greater than or less than the middle element, search in the half of the array that is greater or less than the middle element, and Start the comparison from the middle element as at the beginning. If the array is empty at a certain step, it means it cannot be found. This search algorithm reduces the search range by half with every comparison.

Python uses recursion to achieve binary search

# 定义二分查找函数
def binarySearch(arr,l,r,x):

    # 基本判断
    if r >= 1:

        mid = int(l+(r-l)/2)

        # 元素正好在的中间位置
        if arr[mid] == x:
            return mid

        # 元素小于中间位置的元素,只需要再比较左边的元素
        elif arr[mid] > x:
            return binarySearch(arr,l,mid-1,x)
        
        # 元素大于中间位置的元素,只需要再比较右边的元素
        # else:
        #     return binarySearch(arr,mid+1,r,x)
        else:
            return binarySearch(arr,mid+1,r,x)


    # 不存在
    else:
        return -1


# 测试数组
arr = [2,3,4,10,40,60]
x =10

# 函数调用
result = binarySearch(arr,0,len(arr)-1,x)

if result != -1:
    print("元素在数组中的索引为{}".format(result),'查找元素为{}'.format(arr[result]))
else:
    print("元素不存在")

Guess you like

Origin blog.csdn.net/weixin_45598506/article/details/113781917