Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
def binary_search(sequence,item):
start_index = 0
end_index = len(sequence) - 1 # finds the last index
while start_index <= end_index:
mid_point = start_index + (end_index - start_index)//2 #Finds the mid index of the sequence using the start and end index
mid_point_value = sequence[mid_point]
if mid_point == item:
return mid_point # if item is the mid point the function will end
elif item < mid_point_value:
end_index = mid_point - 1 # if the item is smaller than the mid point a new end index will be set which is the index one before the middle point and the loop continues
else:
start_index = mid_point + 1 # if the item is bigger than the mid point the starting index will be set to the right index of the middle point and then the loop continues
return None
sequence = [1,2,3,4,5,6,7,8,9]
print(binary_search(sequence, 7))