Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. array = [1,3,6,10,15,32,43,46,100,150,170,290] # Given
  2. def BinarySearch(array, target):
  3. n = len(array) # length of array.
  4. left = 0 # at starting are search space is
  5. right = n-1 # full array(from index 0 to n-1)
  6.  
  7.  
  8. # Now remember what we talk about condition for search.
  9. # If are left and right index are same or they are at same positon
  10. # It is time to stop.
  11. # which also means that are left index should not cross right index.
  12.  
  13.  
  14. while left <= right:
  15. mid = (left + right)//2 # middle point we talked about
  16.  
  17. if array[mid] == target:
  18. return mid # returning the index vaue
  19.  
  20. elif array[mid] < target:
  21. left = mid+1 # now your search space is halfed.
  22.  
  23. else:
  24. right = mid-1 # now your search space is halfed
  25. return 'Element does not exist.'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement