Binary search – Python implementation

def binarySearch(array,item):
    if len(array) == 0: return False
    else:
        mid = len(array)//2
        if array[mid] == item:
            return True
        else:
            if item < array[mid]:
                return binarySearch(array[:mid],item)
            else:
                return binarySearch(array[mid+1:],item)
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,]
print(binarySearch(testlist, 3))
print(binarySearch(testlist, 13))
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: