Advertisement
scarygarey

simple_binary_search

Jan 14th, 2020
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. #Binary Search
  2. def binary_search(listnums,search):
  3. found = False
  4. left = 0
  5. right = len(listnums)-1
  6. while left!=right:
  7. midpoint = (left + right)//2
  8. if listnums[midpoint] == search:
  9. found = True
  10. break
  11. if search <= listnums[midpoint]:
  12. right = midpoint
  13. else:
  14. left = midpoint+1
  15. return found,midpoint
  16.  
  17. import random
  18. listnums = []
  19. for i in range(0,50): #will populate 50 random numbers
  20. listnums.append(random.randint(0,100)) # will select 50 random numbers between 1-100)
  21. listnums.sort()
  22. print(listnums) #the numbers randomly selected will appear below
  23.  
  24. print("what integer are you searching for between 1-100?")
  25. search = int(input()) #requires user to input a number
  26.  
  27. found,midpoint = binary_search(listnums,search)
  28. print(found)
  29. print(midpoint+1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement