1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| def binarySearch(array, key, low, high): if high < low: return -1 mid = (low + high)//2
if array[mid] == key: return mid elif array[mid] > key: return binarySearch(array, key, low, mid-1) else: return binarySearch(array,key,mid+1,high)
def binarySearch2(array,key): low,high = 0,len(array)-1
while low <= high: mid = (low + high)//2 if array[mid] < key: low = mid+1 elif array[mid] > key: high = mid-1 else: return mid
return -1
if __name__ == '__main__': array = [1,3,4,5,6,7,8,9] print(binarySearch(array,1,0,len(array)-1)) print(binarySearch2(array,1))
|