Some cases cause my binary search to enter into an Infinite loop
<p>I'm stuck in an infinite loop when searching for anything that is not in the list (but within the range of the list) and anything that is greater than the highest number. For example, when searching for 2 in the list <code>[1,2,5,6]</code>, my function returns index 1, which is correct. If I search for -1, it returns <code>False</code> which is correct. However, if I search for 100 or 4, it gets stuck in an infinite loop.     </p>

<pre><code>def binary_search(a_list, item):

    if not a_list:
        return False

    mid = len(a_list)//2

    print "Middle is: {}".format(a_list[mid])
    print a_list


    while len(a_list) &gt; 0:
        if a_list[mid] == item:
            return mid
        elif a_list[mid] &gt; item:
            return binary_search(a_list[:mid], item)
        elif a_list[mid] &lt; item:
            return binary_search(a_list[mid:], item) + mid
        else:
            return False

a = binary_search([1, 2, 3, 4, 6, 7, 8], 5) # infinite loop
b = binary_search([1, 2, 3, 4, 6, 7, 8], 100) # infinite loop
c = binary_search([1, 2, 3, 4, 6, 7, 8], 8) # works correctly
d = binary_search([1, 2, 3, 4, 6, 7, 8], -2) # works correctly
</code></pre>

<p>Here is the code I used to examine your program. <code>pdb</code> allows you to step through the code one command at a time using <code>s</code> or continue to the next <code>pdb.set_trace()</code> using <code>c</code>. You use it like this:</p>

<pre><code>import pdb

def binary_search(a_list, item):

    if not a_list:
        return False

    mid = len(a_list)//2

    print "Middle is: {}".format(a_list[mid])
    print a_list


    print a_list, item
    pdb.set_trace()

    while len(a_list) &gt; 0:
        if a_list[mid] == item:
            return mid
        elif a_list[mid] &gt; item:
            return binary_search(a_list[:mid], item)
        elif a_list[mid] &lt; item:
            return binary_search(a_list[mid:], item) + mid
        else:
            return False
</code></pre>

<p>Now, there are a number of problems with your program, most notably the combination of looping and recursion. That is rarely correct. I will also point out that every case in your <code>while</code> loop has a return statement, so the <code>while</code> loop only has the effect of causing a search with a list size of <code>0</code> to return nothing at all. I doubt this is what you want.</p>

<p>The second problem is with you trying to return either the index of <code>mid</code> or <code>False</code>. There is no problem with what you're trying to do. The problem is with adding <code>binary_search(...)</code> to <code>mid</code>. The reason this is bad is that in Python, <code>False</code> evaluates to <code>0</code> when you use it like a number. Try running these in an interpreter:</p>

<pre><code>False * 5 # =&gt; 0
False + 5 # =&gt; 5
False == 0 # =&gt; True
False is 0 # =&gt; False
</code></pre>

<p>This means that if your code worked otherwise and there was an unsuccessful search, you would still end up returning an integer answer a lot of the time. The <code>False</code> value would be lost in the addition to <code>mid</code>. To avoid this, the code I give below does not use recursion, so a <code>return False</code> is final. It goes directly to whoever called <code>binary_search</code> in the first place and not to any previous recursive calls. You could still write a recursive solution, but you would almost certainly need to have a comparison like <code>if binary_search(...) is False:</code> somewhere in your code <em>then</em> you would need to worry about the difference between <code>is</code> and <code>==</code> <em>then</em> you might be tempted to use <code>is</code> more frequently, which is a bad idea.</p>

<p>I also believe there are also some issues with <code>a_list[mid:]</code>. I did not confirm this, but I think you would want <code>a_list[mid+1:]</code> to exclude the middle element which you've confirmed is not the element you're looking for. Either way, the alternative code I have does not use slicing at all so I am not going to worry about it. </p>

<p>Here is the code which I believe does what you want.</p>

<pre><code>def binary_search(a_list, item):

    if not a_list:
        return False

    mid = len(a_list)//2
    start = 0 # new and important
    end = len(a_list) # new and important

    while start &lt; end: # new and important
        if a_list[mid] &gt; item:
            end = mid
            mid = (end - start) // 2 # new and important
        elif a_list[mid] &lt; item:
            start = mid + 1
            mid = start + (end - start) // 2 # new and important
        else:
            return mid

    return False
</code></pre>

<p>Note the removal of the recursive calls and the addition of <code>start</code> and <code>end</code>. These keep track of which part of the list you're searching in instead of the list slices you were using before. </p>

python binary-search