AyanUpadhaya

Binary Search In Python

Aug 16th, 2021 (edited)
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. # Binary Search using Python
  2. #=======================================================
  3. # as your list length increases time increases as well
  4.  
  5. # in binary search all the values have to be sorted
  6.  
  7. # first specify the lower bound which is list[0] index
  8.  
  9. # then specify the upper bound which is last element len(list) -1
  10.  
  11. # get mid index = lower+upper/2
  12.  
  13. # check if the mid value is matching with search element
  14.  
  15. # change lower bound or upper bound for the next iteration
  16.  
  17. # check if the value you are searching for is bigger or smaller than mid value
  18.  
  19. # if the value is smaller change the upper bound which means the mid value is the new upper bound
  20.  
  21. # if the value is greater than change the lower bound which means the mid value is the new lower bound
  22.  
  23. # it will improove the speed
  24.  
  25. pos = -1
  26. nums = [4,7,8,12,45,99,100]
  27.  
  28. n = 100
  29.  
  30. def search(numlist,n):
  31.     lowerbound = numlist[0]
  32.     upperbound = len(numlist) - 1
  33.     while lowerbound <= upperbound:
  34.         mid = (lowerbound+upperbound)//2
  35.         if numlist[mid] == n:
  36.             globals()['pos'] = mid
  37.             return True
  38.         else:
  39.             if numlist[mid] < n:
  40.                 lowerbound = mid+1
  41.             else:
  42.                 upperbound = mid-1
  43.     return False
  44.  
  45. if search(nums,n):
  46.     print("Found at ",pos+1)
  47. else:
  48.     print('Not found')
  49.      
  50.  
Add Comment
Please, Sign In to add comment