#binary search
#factorial
def binarySearch(arr, value, low, high):
if low == high :
assert value == arr[high]
return arr[high]
else :
mid = low + ( (high - low) >> 1 )
if value > arr[mid] :
return binarySearch(arr, value, mid+1, high)
else :
return binarySearch(arr, value, low, mid)
# loop
def binarySearchWithLoop(arr, value, low, high):
while low < high :
// 避免数据溢出, 右移一位相当于除以2
mid = low + ( (high - low) >> 1 )
if value > arr[mid] :
low = mid + 1
elif value < arr[mid] :
high = mid - 1
else:
return arr[mid]
return -1
# 数据集,二分查找用于有序序列
arr = [34, 11, -4, 7, 20, -11, 3]
arr.sort()
print "Sorted arr : ", arr
# 函数调用
print binarySearch(arr, 20, 0, len(arr) )
print binarySearchWithLoop(arr, 20, 0, len(arr))
注意: 二分查找的算法注意点为 mid数值的计算,以及high的边界划分。如果high的值为len(arr)则while的条件为 low < high,如果为len(arr) - 1,则为 low <= high。