Dichotomy is a fast-finding method, with a low time complexity and simple logic, which is generally divided by 2 divided by 2 ...
For example, to find the location of a keyword key in an ordered array of arr, first confirm the median or midpoint center of ARR, which is divided into three scenarios:
| 123 |
假如arr[center]>key,说明key在arr中心左边范围;假如arr[center]<key,说明key在arr中心右边范围;假如arr[center]=key,说明key在arr中心。 |
The range shrinks by half each time, writing a while loop to know until it is found.
Binary lookup is very fast and very common, but the only requirement is that the array is ordered
My other blog just introduced the bubble sort can go to see:
| 1 |
http://www.cnblogs.com/TTyb/p/5726151.html |
The code for the dichotomy is as follows:
1 #!/usr/bin/python3.4 2 #-*-Coding:utf-8-*-3 4 def binarysearch (arr, key): 5 # Record array of highest and lowest bits 6 min = 0 7 max = Len (arr)-1 8 9 if key in Arr:10 # Build a dead loop until you find Key11 while True:12 # gets the median 13 # Make sure to add int here, to prevent the list from being even when floating point data occurs. Center = Int ((min + max)/2) # Key on the left of the array F Arr[center] > Key:17 max = center-118 # key on the right of the array elif arr[center] < ke y:20 min = center + 121 # Key in the middle of the array elif arr[center] = = key:23 pr Int (str (key) + "first in array" + STR (center) + "position") return arr[center]25 else:26 print ("No this number!") ) If __name__ = = "__main__": arr = [1, 6, 9, A, a, a, a, $, $, a,, while true:32 Key = input ("Please enter the number you want to find:") if key = = "": Print ("Thank you for using!") ") break36 else:37 binarysearch (ARR, Int (key))
Operation Result:
Original from Ttyb
Python Lookup algorithm: Binary method