Python data structures and algorithms 14th Day "two-point search"

Source: Internet
Author: User

1. How to find two points

Find the fastest speed for a sorted list

2. Code implementation

(1) Recursive implementation

defBinary_search (Alist, item):ifLen (alist) = =0:returnFalseElse: Midpoint= Len (alist)//2ifalist[midpoint]==Item:returnTrueElse:          ifitem<Alist[midpoint]:returnBinary_search (Alist[:midpoint],item)Else:            returnBinary_search (alist[midpoint+1:],item) testlist= [0, 1, 2, 8, 13, 17, 19, 32, 42,]Print(Binary_search (Testlist, 3))Print(Binary_search (Testlist, 13))

(2) Non-recursive implementation

defBinary_search (Alist, item): First=0 Last= Len (alist)-1 whilefirst<=Last:midpoint= (first + last)/2ifAlist[midpoint] = =Item:returnTrueelifItem <Alist[midpoint]: last= Midpoint-1Else: First= Midpoint+1returnfalsetestlist= [0, 1, 2, 8, 13, 17, 19, 32, 42,]Print(Binary_search (Testlist, 3))Print(Binary_search (Testlist, 13))

3. Complexity of Time

Optimal time Complexity: O (1)

Worst time complexity: O (LOGN)

Because it's a dichotomy. How many times does the representation have to be checked, that is Logn

Python data structures and algorithms 14th Day "two-point search"

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.