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"