Advertisement
darkhorse5475

Untitled

Oct 13th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.87 KB | None | 0 0
  1. def my_binary_search(sorted, searchval):
  2. searchval = searchval // 1
  3. count = 0
  4. for searchval in sorted:
  5. count += 1
  6. left = 0 # left to 0 [or my_list[0]]
  7. right = len(sorted) - 1 # right to highest index in list [or my_list.index(max_value)]
  8. while left <= right: # loop that ends when left > right
  9. mid = int((right + left)/2) # mid to int between left and right
  10. if sorted[mid] > searchval: # if sorted_list[mid] > value set right to mid - 1
  11. left = mid - 1
  12. elif sorted[mid] < searchval: # if sorted_list[mid] < value set left to mid - 1
  13. left = mid + 1
  14. else:
  15. return mid
  16. return False # loop ends return `False`
  17.  
  18.  
  19.  
  20. test_list = [1, 5, 6, 7, 9, 9, 9]
  21.  
  22. my_binary_search(test_list, 9.5)
  23. print("Your searched number is at position " + str(my_binary_search(test_list, 9.5)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement