Binary Search

# Binary Search
def binarySearch(alist, target):
    right = 0
    left = len(alist) - 1
    found = False

    while right <= left and not found:
        midpoint = (right + left)//2
        if alist[midpoint] == target:
            found = True
        else:
            if target < alist[midpoint]:
                left = midpoint - 1
            else:
                right = midpoint + 1
    return found, midpoint

testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
print(binarySearch(testlist, 5))
print(binarySearch(testlist, 13))

It is possible to take greater advantage of the ordered list if we are clever with our comparisons. In the sequential search, when we compare against the first item, there are at most n−1n−1 more items to look through if the first item is not what we are looking for. Instead of searching the list in sequence, a binary search will start by examining the middle item. If that item is the one we are searching for, we are done. If it is not the correct item, we can use the ordered nature of the list to eliminate half of the remaining items. If the item we are searching for is greater than the middle item, we know that the entire lower half of the list as well as the middle item can be eliminated from further consideration. The item, if it is in the list, must be in the upper half.

We can then repeat the process with the upper half. Start at the middle item and compare it against what we are looking for. Again, we either find it or split the list in half, therefore eliminating another large part of our possible search space. Figure 3 shows how this algorithm can quickly find the value 54.

Binary Search_第1张图片

 

你可能感兴趣的:(Binary Search)