Good morning, Instead of always using the middle of the list to search (binary search), you can estimate the position of the item to be searched based on the max value (last item), min value (first item) and the search value.
((Assume uniform distribution of the items and the items are sorted.)) This is my code below , do ya"ll have any suggested codes?
def binary_search(seq,item):
"""It uses non recursive method to search the item in the given seq.
It returns the position of item if found, None otherwise"""
left_index=0
right_index=len(seq)-1
while left_index <= right_index: #stop searching when left_index > right_indext
mid_index=(right_index + left_index)//2 #find the mid point
if seq[mid_index]==item:
return mid_index
elif seq[mid_index]>item:
right_index = mid_index -1 #if mid point ele > search ele, move right pointer
else:
left_index = mid_index + 1 #if mid point ele < search ele, move left pointer
return None
a=[1,2,3,4,5,6,7,8,9]
print(binary_search(a,6))