I have made a simple binary search algorithm with the assumptions that the input array is sorted and has only unique values.
def binary_search(input_array, value):
"""
Iterative binary search in sorted array of unique int values.
:param input_array: Sorted array of unique int values.
:type input_array: list<int>
:param value: The int value to search in input_array
:type value: int
:return: The index of value or -1 if it doesn't exist
:rtype: int
"""
result = -1
previous_index_down = 0
previous_index_up = len(input_array)
current_index = int(math.floor(len(input_array[previous_index_down+1:previous_index_up]) / 2))
while True:
if input_array[current_index] == value:
result = current_index
break
elif current_index == previous_index_down or current_index == previous_index_up:
break
elif input_array[current_index] > value:
previous_index_up = current_index
current_index = current_index - int(math.ceil(len(input_array[previous_index_down:previous_index_up+1]) / 2))
elif input_array[current_index] < value:
previous_index_down = current_index
current_index = current_index + 1 + int(math.floor(len(input_array[previous_index_down+1:previous_index_up]) / 2))
if previous_index_down == len(input_array) - 1:
break
return result
For test I used various inputs like the following:
test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
test_val3 = 29
print binary_search(test_list, test_val1)
print binary_search(test_list, test_val2)
print binary_search(test_list, test_val3)
The results appear to be correct, but I am wondering if the implementation can be improved in terms of style and length. Also I don't know if there are inputs that may make it fail.