Binary search algorithm in python

前端 未结 14 929
别那么骄傲
别那么骄傲 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:46

    In the case that needle_element > array[mid], you currently pass array[mid:] to the recursive call. But you know that array[mid] is too small, so you can pass array[mid+1:] instead (and adjust the returned index accordingly).

    If the needle is larger than all the elements in the array, doing it this way will eventually give you an empty array, and an error will be raised as expected.

    Note: Creating a sub-array each time will result in bad performance for large arrays. It's better to pass in the bounds of the array instead.

    0 讨论(0)
  • 2020-12-01 11:47

    array[mid:] creates a new sub-copy everytime you call it = slow. Also you use recursion, which in Python is slow, too.

    Try this:

    def binarysearch(sequence, value):
        lo, hi = 0, len(sequence) - 1
        while lo <= hi:
            mid = (lo + hi) // 2
            if sequence[mid] < value:
                lo = mid + 1
            elif value < sequence[mid]:
                hi = mid - 1
            else:
                return mid
        return None
    
    0 讨论(0)
  • 2020-12-01 11:48

    If you're doing a binary search, I'm guessing the array is sorted. If that is true you should be able to compare the last element in the array to the needle_element. As octopus says, this can be done before the search begins.

    0 讨论(0)
  • 2020-12-01 11:53
    def binary_search(array, target):
        low = 0
        mid = len(array) / 2
        upper = len(array)
    
        if len(array) == 1:
            if array[0] == target:
                print target
                return array[0]
            else:
                return False
        if target == array[mid]:
            print array[mid]
            return mid
        else:
            if mid > low:
                arrayl = array[0:mid]
                binary_search(arrayl, target)
    
            if upper > mid:
                arrayu = array[mid:len(array)]
                binary_search(arrayu, target)
    
    if __name__ == "__main__":
        a = [3,2,9,8,4,1,9,6,5,9,7]
        binary_search(a,9)
    
    0 讨论(0)
  • 2020-12-01 11:55

    You can just check to see that needle_element is in the bounds of the array before starting at all. This will make it more efficient also, since you won't have to do several steps to get to the end.

    if needle_element < array[0] or needle_element > array[-1]:
        # do something, raise error perhaps?
    
    0 讨论(0)
  • 2020-12-01 11:56

    All the answers above are true , but I think it would help to share my code

    def binary_search(number):
        numbers_list = range(20, 100)
        i = 0
        j = len(numbers_list)
        while i < j:
            middle = int((i + j) / 2)
            if number > numbers_list[middle]:
                i = middle + 1
            else:
                j = middle
        return 'the index is '+str(i)
    
    0 讨论(0)
提交回复
热议问题