Binary Search

May 1, 2021, 6:11 p.m.


...

Binary search is a searching algorithm that works efficiently with a sorted list.
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array.
If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half.

Binary search is a searching algorithm that works efficiently with a sorted list.
Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array.
If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half.

def binary_search(container, item, left, right):
  if right<left:
    return -1
  middle_index=(left+right)//2
  if container[middle_index] == item:
    return middle_index
  elif container[middle_index]>item:
    binary_seqrch(container,item,left,middle_index-1)
  elif container[middle_index]<item:
    binary_search(container,item,middle+1,right)



Tags


Comments