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?

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
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.