Binary Search

 An efficient way to search through a large sorted array is the binary sort, which looks for a value by dividing up the array into twos. It finds the midpoint, determines if the value it is looking for is in either the part with the smaller numbers, or the part with the bigger numbers, then does the same thing again with said part. Need 3 counters for it, 'starter' to determine the starting index of the part you want to look through, the 'end' to determine the ending index of the part, and 'midpoint' to calculate the midpoint.

def binary(numberlist, item):
numberlist.sort()
print("Sorted list: ", numberlist)
starter = 0
end = len(numberlist)
while True:
midpoint = round((starter + end)/2)
if numberlist[midpoint] == item:
return midpoint
elif numberlist[midpoint] > item:
end = midpoint
elif numberlist[midpoint] < item:
starter = midpoint
if starter == end:
return None

Comments