Given an array storing integers ordered by value, modify the binary search routine to return the position of the first integer with value K in the situation where K can appear multiple times in the array. Be sure that your algorithm is that is, do not resort to sequential search once an occurrence of K is found.
def Search(array, l, R, K):
if R >= l:
middle = l + (R - l) // 2
if array[middle] == K:
return middle
elif array[middle] > K:
return Search(array, l, middle-1, K)
else:
return Search(array, middle + 1, R, K)
else:
return -1
array = [5, 6, 7, 9, 10, 10, 11, 10]
K = 10
result = Search(array, 0, len(array)-1, x)
if result != -1:
print("The Integer first occurs at index % d" % result)
else:
print("Integer not present in array")
Comments
Are you sure about the answer?
Leave a comment