分別用遞迴、迴圈、bisect實現二叉查詢(python實現)
阿新 • • 發佈:2018-11-10
1、遞迴實現二叉查詢
def binary_search_recursion(lst,target,low,high): if high < low: return None middle = (low + high)//2 if lst[middle] > target: return binary_search_recursion(lst,target,low,middle - 1) elif lst[middle] < target: return binary_search_recursion(lst,target,middle + 1,high) else: return middle
2、迴圈實現二叉查詢
def binary_search_loop(lst,target): low, high = 0,len(lst)-1 while low <= high: middle = (low + high)//2 if lst[middle] > target: high = middle -1 elif lst[middle] < target: low = middle + 1 else: return middle return None
3、bisect實現二叉查詢
import bisect
lst = [1,2,3,4,4,5,6]
print(bisect.bisect_left(lst,4))
print(bisect.bisect_right(lst,4))