# binary.py
# Binary search

# Search for a matching val in items
# If found, return index. If not found, return None
# Use binary search.
def bSearch(val, items):
    mid, min, count = 0, 0, 0
    max = len(items)-1

    while min <= max:
        count += 1                              # Track iterations
        mid = int((max + min) / 2.0)            # Compute next index
        print("[" + str(min) + ", " + str(max) + "] --> " + str(mid))

        if val == items[mid]:                   # Found it
            print(str(val) + " found at index " + str(mid) + " (" + str(count) + " iterations)")
            return mid                          # Return index
        elif val < items[mid]:                  # val is before items[mid]
            max = mid - 1                       # Reset max to item before mid
        else:                                   # val is after items[mid]
            min = mid + 1                       # Reset min to item after mid

    # If we get this far, val was not found.
    print(str(val) + " not found in " + str(count) + " iterations")
    return None

# Fill list with letters
letters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
           "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"]

# Search for a letter
bSearch("Z", letters)
