Search code examples
pythonbinary-search

Binary Search doesn't give correct result


I have a problem with the following code. I try to find the given k element in the array with binary search. But function binSearch doesn't return a result. I found a similar code in StackOverflow and followed the same but it didn't matter.

def binSearch(s, k, l, r):
    m = (l+r)//2
    if l <= r: 
        if k > s[m]:
            return binSearch(s,k,m+1,r)
        elif k < s[m]:
            return binSearch(s,k,l,m)
        elif s[m] == k:
            return m
    else:
        return -1


s = [34, 23, 12, 45, 3, 2, 76, 1, 4, 3, 6, 7]
l = 0
r = len(s)
k = 12
s.sort()
binSearch(s, k, l, r)

Solution

  • your code is working fine, it is giving the index of the sorted array element not the original list index. you have used s.sort() so ur list s is updated sort list and you are getting that element index from this sorted list