Python二分查找
上次用python写二分查找,习惯性的就写递归函数,结果被坑了,重新写了一份
代码:
def bin_searth(in_list, num):
if(not in_list):
return -1
length = len(in_list)
index = length/2
begin = 0
end = length - 1
while(True):
if(in_list[index] == num):
return index
else:
if(length == 1):
return -1
if(in_list[index] > num):
end = index - 1
elif(in_list[index] < num):
begin = index + 1
index = (begin + end)/2
length = end - begin + 1
然后看了下别人的实现,据说这段代码出自《代码之美》(Beautiful Code)http://www.oschina.net/code/snippet_250815_10547
代码:
def BinarySearch(a, target):
low = 0
high = len(a) - 1while low <= high:
mid = (low + high) // 2
midVal = a[mid]
if midVal < target:
low = mid + 1
elif midVal > target:
high = mid - 1
else:
return mid
return -1
果然比自己的简洁很多,学习了