Advertisement
182days

Binary Search Example

May 10th, 2016
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. # BinarySearch.py
  2. # Alan Richmond, Python3.codes
  3.  
  4. import random
  5.  
  6. anum = 9                    # number to search for
  7. size = 10                   # size of random array
  8. array = random.sample(list(range(1, 20)), size)  # get some random numbers
  9. #array = sorted(array)       # sorted() returns a new list
  10. #array.sort()               # sort() sorts in-place
  11. print(anum, array)          # show us what you've got
  12.  
  13. #    Search for number in array
  14. def binary_search(number, array, lo, hi):
  15.  
  16.     if hi < lo: return -1       # no more numbers
  17.     mid = (lo + hi) // 2        # midpoint in array
  18.     if number == array[mid]:
  19.         return mid                  # number found here
  20.     elif number < array[mid]:
  21.         return binary_search(number, array, lo, mid - 1)     # try left of here
  22.     else:
  23.         return binary_search(number, array, mid + 1, hi)     # try above here
  24.  
  25. def my_search(anum, array):     # convenience interface to binary_search()
  26.     return binary_search(anum, array, 0, len(array) - 1)
  27.  
  28. pos = my_search(anum, array)
  29. if pos < 0:
  30.     print("not found")
  31. else:
  32.     print("found at position", pos)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement