1

I'm trying to implement a binary search; it takes an ordered list, takes the mid value, compares it to the target value, then sub-lists either above or below the mid value until the target is found or is missing from the list. However, for some reason, I always get 'None' returned unless the midpoint is the target. I'm not sure what's going wrong.

def bisect(list,target):


    print list
    split= list[len(list)//2]
    print "Split value : " + str(split)  

    if target==split: 
        return "target" 

    elif target<split:
        bisect(list[:split],target) 

    elif target>split:
        bisect(list[(split):],target)

a= [1,2,3,4,5,6,7,8,9,10]       
print bisect(a,2)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Split value : 6
[1, 2, 3, 4, 5, 6]
Split value : 4
[1, 2, 3, 4]
Split value : 3
[1, 2, 3]
Split value : 2
None

It looks like the last compare between split and the target value isn't occurring?

4
  • 3
    why not use the bisect module? Commented May 10, 2013 at 19:14
  • @FredrikPihl or at least - look at how the bisect module implements its functions for comparison Commented May 10, 2013 at 19:15
  • 2
    As a side note: Calling your list list is confusing, and means you can't use the type/constructor of the same name within your function. Commented May 10, 2013 at 19:24
  • @abarnert true I'm not using the type so it's causing problems, but the way I did it is bad form. I will change it. Commented May 10, 2013 at 19:34

1 Answer 1

4

Two problems:

  1. When you recurse by calling bisect, you still need to return the value of the call by doing return bisect(list[:split],target).

  2. split is an element of list, not an index, so list[:split] won't do what you think. Use list[:len(list)//2] instead, and likewise change list[split:] to list[len(list)//2:].

Sign up to request clarification or add additional context in comments.

2 Comments

It would be nicer to do splitpoint = len(list)//2, then do split = list[splitpoint] and use list[:splitpoint] and list[splitpoint:], instead of repeating the same expression 3 times. But otherwise, great answer.
@abarnert list[:splitpoint] and list[splitpoint+1:]. Omitting the +1 can lead to infinite recursion.

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.