Binary search algorithm in python

前端 未结 14 1193
别那么骄傲
别那么骄傲 2020-12-01 11:23

I am trying to implement the binary search in python and have written it as follows. However, I can\'t make it stop whenever needle_element is larger than the largest elemen

14条回答
  •  时光说笑
    2020-12-01 11:35

    This is a tail recursive solution, I think this is cleaner than copying partial arrays and then keeping track of the indexes for returning:

    def binarySearch(elem, arr):
        # return the index at which elem lies, or return false
        # if elem is not found
        # pre: array must be sorted
        return binarySearchHelper(elem, arr, 0, len(arr) - 1)
    
    def binarySearchHelper(elem, arr, start, end):
        if start > end:
            return False
        mid = (start + end)//2
        if arr[mid] == elem:
            return mid
        elif arr[mid] > elem:
            # recurse to the left of mid
            return binarySearchHelper(elem, arr, start, mid - 1)
        else:
            # recurse to the right of mid
            return binarySearchHelper(elem, arr, mid + 1, end)
    

提交回复
热议问题