2

I have been ,wanting to do binary search (by recursion) , and I dont know why my code is not working... Can anyone pls, correct my code and tell the reason why it is not working??

As you can look in my code, i am slicing the string per recursion, and at last when the target is found i will return the position of the target..

def binary(n,target):
    n.sort()
    mid = (0 + (len(n)-1))//2
    if target == n[mid]:
        return mid
    elif target < n[mid]:
        return binary(n[:mid],target)
    elif target > n[mid]:
        return binary(n[mid:],target)

This is the error message i am recieving... RecursionError: maximum recursion depth exceeded while calling a Python object.

2
  • Print out the n and mid to see what is going on? Also, you're unnecessarily sorting your list (segment) many times. I'm assuming mid becomes 0. Commented Aug 14, 2019 at 7:08
  • Check this link geeksforgeeks.org/binary-search Commented Aug 14, 2019 at 7:13

2 Answers 2

1

There are two problems, both of them are on the last line:

def binary(n, target):
    n.sort()
    mid = (0 + (len(n) - 1)) // 2
    if target == n[mid]:
        return mid
    elif target < n[mid]:
        return binary(n[:mid], target)
    elif target > n[mid]:
        return mid + 1 + binary(n[mid + 1:],target)
                ^^^^^^^^                ^
  1. since you're slicing, and in order to provide the index in the original sorted list, we need to keep track of the indexes we "lose" while recursing
  2. The complete to n[:mid] is n[mid+1:] - not n[mid:] because you already checked the target (in mid) and want to remove it from future iterations - this is, by the way, what causes the infinite loop!

Since we slice the list at mid+1 we need to add mid+1 before calling recursively, in order to preserve the index of the item on the right-side of the list:

[1,2,3,4,5]
     ^ say we slice here and get [4,5]
       we want to save the indexes so we'll add mid (2) + 1 since now in [4,5] the item 4 will get the index zero

Comment: by calling n.sort() upon every iteration we "lose" all the advantage of binary search since, even after the list is sorted, to re-sort it will take at least O(n). So if we need to sort first, we might as well just iterate the array until the item is found/not-found. Or, if we insist on sorting, do it only once and only then call recursively:

n.sort()
binary(n, 2)

where binary does't include the sorting anymore:

def binary(n, target):
    mid = (0 + (len(n) - 1)) // 2
    if target == n[mid]:
        return mid
    elif target < n[mid]:
        return binary(n[:mid], target)
    elif target > n[mid]:
        return mid + 1 + binary(n[mid + 1:], target)
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah it worked...! Can you please tell me... Why we are doing mid + 1 + binary (n[mid + 1 :], target)??? I am unable to understand...
@AryanKumar the explanation is in #2 above
0

Your midpoint calculation is too aggressive:

Consider n = [1, 2, 3] and target = 3. mid (len(n)-1//2) will then be 0, when surely it should be 1 or 2. The issue stems from you subtracting 1 from the length, and then dividing the result by 2.

Since you anyways do integer division, there is no need for subtracting one:

def binary(n,target):
    n.sort()
    mid = len(n)//2
    ...

There is also the issue of sorting the list (segment) every time binary is entered, which is unnecessary. You could write a wrapper function that sorts the list once and then calls the inner recursive function:

def binary(n, target):
    return _binary(sorted(n), target)

Then just rename your original function to _binary.

Finally, when cutting from the left, you'll need to make sure to keep track of the lost number that you need to add to the index:

elif target > n[mid]:
    return mid + binary(n[mid:],target)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.