Python Binary Search Algorithm recursion implementation method, python Recursion
This example describes the Recursive Implementation of the python binary search algorithm. 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.