简体   繁体   中英

Implementing the Binary Search algorithm in python

I am new into python and i am trying to implement binary search via recursion , I could see the solution of internet but i tried all way myself because i wanted to learn , so this is my approach :

y=7
count=0
def hello(x):

    while len(x)>0:
        for i in x:
            a=len(x)//2

            if y<x[a]:
                print("left_most_side", a)
                return hello(x[:a])

            elif y==x[a]:
                print("middle", a)
                return a
            elif y>x[a]:
                print("right_most_side", a)
                return hello(x[a:])


        return x

hello([1,2,3,4,5,6,7])

Its working perfects and giving the output as expected but issue is , its printing the index of bi-sectioned list, while i need the index of origional list. example : a=[1,2,3,4] it bisection this and now [1,2] and [3,4] and now if i had to find 4 then it will print 4 is at position 0 , answer is correct but only in bisectioned list , while the correct answer is "4" is in origional list at position 3 so it should print 3 , that's the problem i am facing.

As mentioned in my comment, I would recommend passing the entire list, along with the upper and lower bounds to search. This will take care of the index issue.

Furthermore, please do not have your function work with global variables. It's bad practice.

def hello(x, key, l, r):
     if l < r:
        a = (l + r) // 2
        if key < x[a]:
            return hello(x, key, l, a + 1)

        elif key > x[a]:
            return hello(x, key, a + 1, r)

        else:
            return a

     else:
          return -1

In [288]: src = [1,2,3,4,5,6,7]

In [289]: hello(src, key=7, l=0, r=7) 
Out[289]: 6

In [290]: hello(src, key=0, l=0, r=7) 
Out[290]: -1

In [291]: hello(src, key=1, l=0, r=7) 
Out[291]: 0

Use left and right to track the array bounds as it passes through recursion like this

y=7

def hello (x, left, right, query):
    if right >= left:
        mid = left + (right - left)/2
        if x[mid] == query:
            return mid
        elif x[mid] > query:
            return hello(x, left, mid-1, query)
        else:
            return hello(x, mid+1, right, query)
    else:
        # we found nothing
        return -1
arr = [1,2,3,4,5,6,7]

print hello(arr,0,len(arr),y)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM