Permalink
Cannot retrieve contributors at this time
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?
210CT-CW/binarySearch.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
18 lines (15 sloc)
941 Bytes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |