一、二分法查找
有一个【有序数列】中查找一个特定的数字,用顺序查找无疑是最没效率的方法了,直接找数列中间的呢个数字与被查找数(key)相比较,如果这个数字与被查找数(key)小,无疑被查找数一定是在这个有序数列的后半部分,否则被查找数一定在这个有序数列的前半部分
二、输出结果
三、代码实现:
import random
import timeit
def randomList(n):
iList = []
for i in range(n):
iList.append(random.randrange(0,1000))
return iList
def quicksort(iList):
if(len(iList)<=1):
return iList
left = []
right = []
for i in iList[1:]:
if i<=iList[0]:
left.append(i)
else :
right.append(i)
return quicksort(left)+[iList[0]]+quicksort(right)
def sequentialSearch(iList,key):
#print("iList is: %s" %str(iList))
#print("find the number: %d" %key)
ilen = len(iList)
for i in range(ilen):
#print(iList[i])
#print(key)
if iList[i] == key:
return i
#print(i)
return -1
def binarySearch(iList,key):
ilen = len(iList)
right = ilen-1
left = 0
while right-left > 1:
mid = (right+left)//2
print(mid,key,iList[mid])
if key>iList[mid]:
left = mid
elif key<iList[mid]:
right = mid
else:
return mid
if key == iList[left]:
return left
elif key == iList[right]:
return right
else:
return -1
if __name__ == "__main__":
iList = quicksort(randomList(20))
print(iList)
keys=[random.choice(iList),random.randrange(min(iList),max(iList))]
for key in keys:
num = binarySearch(iList,key)
if(num>=0):
print("%d number is %d\n"%(key,num))
else:
print("%d the key number is not find\n"%key)
#print(timeit.timeit("selectsort(iList)","from __main__ import selectsort,iList",number=100))