标签:item 代码 guess 返回值 函数返回值 perm 直接 python 作用
作用:二分查找适用于有序的的数组或列表中,如果列表及数组中有n个元素,通过二分查找查询某一元素的位置需要的步骤是log2(n)(注:该log的底数是2)
def binary_search(list,item): low = 0 high = len(list)-1 #python数组ID从0开始,与matlab不同、 t = 0 while low <= high: t = t + 1; mid = round((low + high)/2) guess = list[mid] if guess == item: return (mid,t) if guess > item: high = mid-1 else: low = mid + 1 return None #python关键字None,相当于matlab的NaN my_list = range(1,101) value = binary_search(my_list,1) print ("Search Num:",value[1],‘Index Position‘,value[0])
运行后结果:
Search Num: 6 Index Position 0
注意事项:
函数实现代码:
function [count,out] = binary_search(list,item) %list:所要查找的数组一维行向量 %item:查找的元素 low = 1; high = length(list); t = 0; while low <= high t = t+1; mid = round((low+high)/2); guess = list(1,mid); if guess == item out = mid; count = t; break; else if guess > item high = mid - 1; if high<low out = ‘None‘; break; end else low = mid + 1; if high<low out = ‘None‘; break; end end end end
测试用代码:
n = 100; data = randperm(n); data = sort(data); [t,v] = binary_search(data,100); str = [‘search num:‘,num2str(t),‘; ‘,‘Index Position:‘,num2str(v)]; disp(str);
运行后结果:
search num:6; Index Position:100
注意事项
标签:item 代码 guess 返回值 函数返回值 perm 直接 python 作用
原文地址:https://www.cnblogs.com/GavinDu/p/12320894.html