Advertisement
brendan-stanford

binary_search

Aug 25th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. from random import randint
  2.  
  3. #collect user input to determine size of random list
  4. n = int(input("Size of random number list:"))
  5. start_list = [randint(0, 100) for i in range(n)]
  6.  
  7. #demo list for item recognition testing
  8. #start_list = [9,8,7,6,5,4,3,2,1,0]
  9.  
  10. #sort list
  11. sorted_list = sorted(start_list)
  12.  
  13. #binary search cuts dataset in half after each iteration until midpoint is equal to value
  14. #(neither greater or less); otherwise loop terminates, and False should be returned as value not present
  15. def binary_search(dataset, value):
  16. n = len(dataset)
  17. left = 0
  18. right = n-1
  19. while left <= right:
  20. mid = int((left + right) / 2)
  21. if dataset[mid] > value:
  22. right = mid - 1
  23. elif dataset[mid] < value:
  24. left = mid + 1
  25. else:
  26. return mid+1
  27. return False
  28.  
  29. #collect user input for value to search for in binary_search function
  30. guess = int(input("Value to search for:"))
  31. search = binary_search(sorted_list, guess)
  32.  
  33. #report on whether value found
  34. if search != False:
  35. print(guess, "found at position", search)
  36. else:
  37. print(guess, "not found.")
  38.  
  39. #print original and sorted list for user inspection
  40. print(start_list)
  41. print(sorted_list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement