'i tried out binary search python problem bt the otp is not crt

pos = -1

def search(list,n):

low=0
u = len(list)-1

while low <= u:
    mid = (low+u)//2

    if mid == n:
        globals()["pos"]=mid
        return True
    else:
        if list[mid] < n:
            low = mid+1
        else:
            u = mid-1
return False

list = [1,2,3,4,5,6,7,8,9,111,229,353,474,545,676,977,87778,999999] n = 676

if search(list,n): print('found at',pos+1) else: print("not found")

this is the code i written bt i cant find out the problem with this



Solution 1:[1]

First if inside the while loop compares the position (mid) with the number itself (n):

if mid == n:

There you need to compare the number on that position (list[mid]) with n:

if list[mid] == n:

If you update this line it will work as expected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan Constantinescu