Binary search if array contains duplicates

后端 未结 5 1193
慢半拍i
慢半拍i 2021-02-11 04:05

Hi,

what is the index of the search key if we search for 24 in the following array using binary search.

array = [10,20,21,24,24,24,24,24,30,40,45]
         


        
5条回答
  •  粉色の甜心
    2021-02-11 04:43

    It works in both unique and non-unique array.

    def binary_search(n,s):
      search = s
      if len(n) < 1:
        return "{} is not in array".format(search)
      if len(n) == 1 and n[0] != s:
        return "{} is not in array".format(search)
      
      mid = len(n)//2
      ele = n[mid]
      if search == ele:
        return "{} is in array".format(search)
      elif search > ele:
        return binary_search(n[mid:],search)
      else:
        return binary_search(n[:mid],search)
    

提交回复
热议问题