> You're going to write a binary search function.
> You should use an iterative approach - meaning
> using loops.
> Your function should take two inputs:
> a Python list to search through, and the value
> you're searching for.
> Assume the list only has distinct elements,
> meaning there are no repeated values, and
> elements are in a strictly increasing order.
> Return the index of value, or -1 if the value
> doesn't exist in the list.
>
```
"""You're going to write a binary search function.
You should use an iterative approach - meaning
using loops.
Your function should take two inputs:
a Python list to search through, and the value
you're searching for.
Assume the list only has distinct elements,
meaning there are no repeated values, and
elements are in a strictly increasing order.
Return the index of value, or -1 if the value
doesn't exist in the list."""
def binary_search(input_array, value):
"""Your code goes here."""
new_input_list = input_array
while new_input_list:
if len(new_input_list)%2!=0:
middle_element = int(len(new_input_list)/2)
if value == new_input_list[middle_element]:
return middle_element
elif value > new_input_list[middle_element]:
new_input_list = new_input_list[middle_element+1::]
elif value < new_input_list[middle_element]:
new_input_list = new_input_list[:middle_element:]
else:
middle_element = int(len(new_input_list)/2-1)
if value == new_input_list[middle_element]:
return middle_element
elif value > new_input_list[middle_element]:
new_input_list = new_input_list[middle_element+1::]
elif value < new_input_list[middle_element]:
new_input_list = new_input_list[:middle_element:]
return -1
test_list = [1,3,9,11,15,19,29]
test_val1 = 25
test_val2 = 15
test_val3 = 9
#print (binary_search(test_list, test_val1))
#print (binary_search(test_list, test_val2))
print (binary_search(test_list, test_val3))
```