Binary search algorithm in python

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

    Without the lower/upper indexes this should also do:

    def exists_element(element, array):
        if not array:
            yield False
    
        mid = len(array) // 2
        if element == array[mid]:
            yield True
        elif element < array[mid]:
            yield from exists_element(element, array[:mid])
        else:
            yield from exists_element(element, array[mid + 1:])
    

提交回复
热议问题