本文實例講述了python二分查找演算法的遞歸實作方法。分享給大家供大家參考,具體如下:
這裡先提供一段二分查找的程式碼:
def binarySearch(alist, item): first = 0 last = len(alist)-1 found = False while first<=last and not found: midpoint = (first + last)//2 if alist[midpoint] == item: found = True else: if item < alist[midpoint]: last = midpoint-1 else: first = midpoint+1 return found testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42,] print(binarySearch(testlist, 3)) print(binarySearch(testlist, 13))
最近才喜歡遞歸的簡單明了,所以修改成遞歸的方法:
def binSearch(lst, item): mid = len(lst) //2 found = False if lst[mid] == item: found = True return found if mid == 0: #mid等于0就是找到最后一个元素了。 found = False return found else: if item > lst[mid]: #找后半部分 #print(lst[mid:]) return binSearch(lst[mid:], item) else: return binSearch(lst[:mid], item) #找前半部分
測試通過。
更多python二分查找演算法的遞迴實作相關文章請關注PHP中文網!