Recursive Implementation of the python Binary Search Algorithm

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.