In this paper, the recursive implementation method of Python binary search algorithm is described. Share to everyone for your reference, as follows:
Here is the code for a two-point lookup first:
def binarysearch (Alist, item): First = 0 last =len (alist)-1 found = False while First<=lastand not Found:midpoint = (first + last)//2if alist[midpoint] = = Item: found = TrueElse: If Item < Alist[midpoint]: last = midpoint-1 else: First = midpoint+1 return foundtestlist = [0, 1, 2, 8,, +, +,, 42,]print (Binar Ysearch (Testlist, 3)) print (BinarySearch (testlist, 13))
Recently, it is simple and straightforward to like recursion, so modify the recursive method:
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:]) Returnbinsearch (lst[mid :], item) Else: Returnbinsearch (Lst[:mid], item) #找前半部分
Test passed.
Read more about Python topics: python Regular expression Usage summary, Python data structure and algorithm tutorials, Python socket Programming Tips Summary, Python function Usage tips summary, "How-to" Python string manipulation Tips Summary, Python Introductory and Advanced classic tutorials, and Python file and directory operations tips
I hope this article is helpful for Python program design.