This article mainly introduces the Recursive Implementation Method of the python binary search algorithm, and analyzes the implementation skills of the Python Binary Search Algorithm in the form of examples, for more information about how to implement python binary search, see the following example. We will share this with you for your reference. The details are as follows:
Here we provide a binary search code:
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, 13, 17, 19, 32, 42,]print(binarySearch(testlist, 3))print(binarySearch(testlist, 13))
Recently, I like the simple and clear recursion, so the method is modified to recursive:
Def binSearch (lst, item): mid = len (lst) // 2 found = False if lst [mid] = item: found = True return found if mid = 0: # If the value of mid is 0, the last element is found. Found = False return found else: if item> lst [mid]: # Find the second half # print (lst [mid:]) returnbinSearch (lst [mid:], item) else: returnbinSearch (lst [: mid], item) # Find the first half
Test passed.