0

i'm having problems with a binary search in a list...

def binarySearch(list1,faces):
    first = 0
    last = len(list1) - 1
    while first <= last:
        mid = (first + last) / 2
        if faces == list1[mid]:
            return mid
        elif faces < list1[mid]:
            last = mid - 1
        else:
            first = mid + 1
    return -1

and i'm searching through this list:

['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']

whenever i search for the values "10", "Queen" and "Ace", the function always returns a -1 (signifying that the item is not found in the list), when clearly, the items exist in the list.

any help?

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by woooee
0

The list has to be in order, so sort it as the first statement in the function

def binarySearch(list1,faces):
    list1.sort()
    first = 0
    last = len(list1) - 1
    while first <= last:
        mid = (first + last) / 2
        if faces == list1[mid]:
            return mid
        elif faces < list1[mid]:
            last = mid - 1
        else:
            first = mid + 1
    return -1
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.