Binary search algorithm in python

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

    Returning a boolean if the value is in the list.

    Capture the first and last index of the list, loop and divide the list capturing the mid value. In each loop will do the same, then compare if value input is equal to mid value.

    def binarySearch(array, value):
      array = sorted(array)
      first = 0
      last = len(array) - 1
    
      while first <= last:
        midIndex = (first + last) // 2
        midValue = array[midIndex]
    
        if value == midValue:
          return True
        if value < midValue:
          last = midIndex - 1
        if value > midValue:
          first = midIndex + 1
      return False
    

提交回复
热议问题