Advertisement
zhongnaomi

binary search to find a tennis ball

Feb 15th, 2019
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.63 KB | None | 0 0
  1. balls=[40,43,56,67,72,76,210,218,223,239]
  2. tennisball=67
  3. def binary_search(sorted_list,value):
  4.    
  5.    
  6.     movect = 1
  7.     left =0
  8.     right = len(sorted_list)-1
  9.     while left <= right :
  10.         mid = int((left + right)/2)
  11.        
  12.        
  13.         if sorted_list[mid]<value:
  14.             left = mid+1
  15.             movect += 1
  16.         elif sorted_list[mid]>value:
  17.             right = mid-1
  18.             movect +=  1
  19.         else:
  20.             return mid, movect
  21.     return False
  22.  
  23. pos,mov2=binary_search(balls,tennisball)
  24. print('The tennis ball is the ', str(pos+1),' ball in the shelf.')
  25. print('binary search took ' ,str(mov2),'times to move')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement