Answer the question
In order to leave comments, you need to log in
How to add element existence check to binary search algorithm?
There is a binary search algorithm that, depending on the value of the last variable, returns the first or last occurrence of an element in an array
def binary_search(l, key, last):
low = 0
high = len(l)-1
while low <= high:
mid = (low + high) // 2
midVal = l[mid];
if (midVal < key or (last and midVal == key)): low = mid + 1
elif (midVal > key or ((not last) and midVal == key)): high = mid - 1
return high if last else low
if key in list
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question