(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))
(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))
- Optimal time Complexity: O (1)
- Worst time complexity: O (LOGN)
Binary search also known as binary lookup, the advantages are less than the number of comparisons, Find Fast, the average performance is good, the disadvantage is that the unknown origin table is ordered table, and insert delete difficult.
Python Two-point lookup