简体   繁体   中英

Why is nothing being outputted for this binary search code?

I have code that supposed to do a binary search on a list . The code is executed but nothing is returned. I copied this from a book word for word. I don't know if it's pycharm or if the code is wrong. can you help?

def binarySearch(aList, item):
    start = 0
    end = len(aList) - 1
    index = -1
    found = False
    while start <= end and found:
        mid = (start + end) / 2
        if aList[mid] == item:
            found = True
            index = mid
            print("index at " + str(index))
            return index
        elif aList[mid] < item:
            start = mid + 1
        else:
            end = mid - 1
        return index

nums = [1, 4, 6, 27, 35, 36, 52, 60, 72, 80]

num = 35

binarySearch(nums, num)

There are a few mistakes/improvements:

  1. Your found variable is redundant (mentioned in the comments).
  2. You need integer division ('//' instead of '/').
  3. Remove the return statement at the end of while loop.
  4. No need to have an index variable, if not found just return -1 in the end.

So, the fixed version would be:

def binarySearch(aList, item):
    start = 0
    end = len(aList) - 1
    while start <= end:
        mid = (start + end) // 2
        if aList[mid] == item:
            print("index at " + str(mid))
            return mid
        elif aList[mid] < item:
            start = mid + 1
        else:
            end = mid - 1
    return -1

nums = [1, 4, 6, 27, 35, 36, 52, 60, 72, 80]

num = 35

binarySearch(nums, num)

First of all, your return is inside the while loop, hence why nothing is returned.

After fixing that you'll still return the default index value you sat (-1), and that's because you never enter the loop because the found value is initially "False".

After fixing that you'll still get an error, this time however is easier to figure out, which is that list indices must be integers or slices, not float . That's because your mid can be a float. To fix that wrap it in an int().

Finally, your code should look something like this

def binarySearch(aList, item):
    start = 0
    end = len(aList) - 1
    index = -1
    found = False
    while start <= end and not found:
        mid = int((start + end) / 2)
        if aList[mid] == item:
            found = True
            index = mid
            print("index at " + str(index))
            return index
        elif aList[mid] < item:
            start = mid + 1
        else:
            end = mid - 1
    return index

nums = [1, 4, 6, 27, 35, 36, 52, 60, 72, 80]

num = 35

print(binarySearch(nums, num))

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