Answer to Question #298906 in Python for lemhs

Question #298906

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.


1
Expert's answer
2022-02-18T01:22:59-0500
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")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

lehms
18.02.22, 11:49

Are you sure about the answer?

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS