Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- array = list(range(1000000))
- # array.index(2)
- # 4 function calls in 0.065 seconds
- def get_binary_index(array, element):
- l = 0
- r = len(array) - 1
- while l <= r:
- m = (l + r) // 2
- if array[m] == element:
- return m
- if array[m] < element:
- l = m + 1
- else:
- if array[m] > element:
- r = m - 1
- return -1
- # get_binary_index(array, 2)
- # 5 function calls in 0.062 seconds
- def binary_search(array, number):
- array_length = len(array)
- min_index = 0
- max_index = array_length - 1
- current_index = array_length // 2
- while True:
- if array[current_index] == number:
- return(current_index)
- break
- if array[current_index] > number:
- max_index = current_index
- current_index = (max_index - min_index) // 2
- continue
- if array[current_index] < number:
- min_index = current_index
- current_index += (max_index - min_index) // 2 + (max_index - min_index) % 2
- else:
- return(-1)
- # binary_search(array, 2)
- # 5 function calls in 0.062 seconds
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement