Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def my_binary_search(sorted, searchval):
- searchval = searchval // 1
- count = 0
- for searchval in sorted:
- count += 1
- left = 0 # left to 0 [or my_list[0]]
- right = len(sorted) - 1 # right to highest index in list [or my_list.index(max_value)]
- approx = left
- while left <= right: # loop that ends when left > right
- mid = int((right + left)/2) # mid to int between left and right
- if sorted[mid] > searchval: # if sorted_list[mid] > value set right to mid - 1
- left = mid - 1
- elif sorted[mid] < searchval: # if sorted_list[mid] < value set left to mid - 1
- left = mid + 1
- else:
- approx = mid
- break
- return approx
- test_list = [1, 5, 6, 7, 9, 9, 9]
- my_binary_search(test_list, 8)
- print("Your searched number is at position " + str(my_binary_search(test_list, 8)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement