Recursive implementation method of Python binary lookup algorithm

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

  • Related Article

    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.