Binary search algorithm
If you have a list that lets you find 66 of the locations from this list, what do you want to do?
L = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
You say so easy!
L.index (66) ...
We can find this using the index method, because Python helps us find the way. If, the index method does not give you the use of ... Can you still find this 66?
L = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88= 0 for in L: if num = =: print(i) i+=1
View Code
The above method realizes the location of 66 from a list.
But how do we find this number now? is not the cycle of this list, one to find AH? If we have a very long list, and we have a good hundreds of thousands of-digit number, do we need to compare a hundred thousand of times if we have bad luck? It's so inefficient, we have to think of a new way.
Binary search algorithm
L = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]
Do you observe this list, which is not an ordered list of small to large sort?
If that's the case, if I'm looking for a larger number than the middle of the list, am I just going to look in the back half of the list?
This is the binary search algorithm !
So how do we implement it in the code?
Simple version of Binary method
L = [2,3,5,10,15,16,18,22,26,30,32,35,41,42,43,55,56,66,67,69,72,76,82,83,88]deffunc (L,aim): Mid= (Len (l)-1)//2ifL:ifAim >L[mid]: func (L[mid+1:],aim)elifAim <L[mid]: func (L[:mid],aim)elifAim = =L[mid]:Print("Bingo", mid)Else: Print('I can't find them .') func (L,66) func (L,6)
View Code
Two-way version of the upgrade
defSearch (num,l,start=none,end=None): Start= StartifStartElse0 End= EndifEndElseLen (L)-1Mid= (End-start)//2 +StartifStart >End:returnNoneelifL[mid] >Num:returnSearch (num,l,start,mid-1) elifL[mid] <Num:returnSearch (num,l,mid+1, end)elifL[mid] = =Num:returnMid
View Code
10-Two-point lookup algorithm