Advertisement
darkhorse5475

Untitled

Oct 14th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.88 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. approx = left
  9. while left <= right: # loop that ends when left > right
  10. mid = int((right + left)/2) # mid to int between left and right
  11. if sorted[mid] > searchval: # if sorted_list[mid] > value set right to mid - 1
  12. left = mid - 1
  13. elif sorted[mid] < searchval: # if sorted_list[mid] < value set left to mid - 1
  14. left = mid + 1
  15. else:
  16. approx = mid
  17. break
  18. return approx
  19.  
  20.  
  21.  
  22. test_list = [1, 5, 6, 7, 9, 9, 9]
  23.  
  24. my_binary_search(test_list, 8)
  25. print("Your searched number is at position " + str(my_binary_search(test_list, 8)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement