The basic idea of Binary Search:
Prerequisites: sequential storage and ordered elements
(1) determine the midpoint of the interval: Mid = (low + high)/2
Min represents the node location in the middle of the interval, low represents the leftmost node location in the interval, and high represents the rightmost node location in the interval
(2) compare the value of a To be queried with the keyword of the node mid (R [Mid]. Key is used below). If the value is equal, the search is successful; otherwise, a new search interval is determined:
If R [Mid]. key> A, the order of the table is known, R [Mid]. the values on the right of the key are greater than a, so if a keyword equal to a exists, it must be in R [Mid]. the table on the left of the key. In this case, high = mid-1
If R [Mid]. Key <A, it is equal to the key of A. If it exists, it must be in the table on the right of R [Mid]. Key. At this time, low = mid
If R [Mid]. Key = A, the search is successful.
(3) For the next search interval, Repeat steps (1) and (2)
(4) During the search process, low increases gradually and high decreases gradually. If High is less than low, the search fails.
Average search length = log2 (n + 1)-1
Note: although the binary search efficiency is high, you need to sort the table by keywords. Sorting itself is a very time-consuming operation, so the bipartite method is more suitable for sequential storage structures. To keep the table in order, a large number of nodes must be moved in the sequence structure. Therefore, binary search is especially suitable for linear tables that are rarely changed once created and frequently needed to be searched.
The following is a non-recursive and recursive Python Implementation of Binary Search:
#!/use/bin/env python
#encoding=gbk """The array is ordered, binary search""" def binarySearch(): list = [ - 7 , - 5 , - 3 , 0 , 1 , 3 , 5 , 7 ] target = 7 low = 0 high = len ( list ) count = 0 while low < = high: count + = 1 mid = (low + high) / 2 if list [mid] = = target: return list [mid], count elif list [mid] > target: high = mid - 1 else : low = mid + 1 return None , count def iter (low, high, count, list , target): mid = (low + high) / 2 count + = 1 if list [mid] = = target: return target,count elif list [mid] > target: return iter (low, mid - 1 , count, list , target) else : return iter (mid + 1 , high, count, list , target) """The array is ordered, binary search interation.""" def binarySearchIte(): list = [ - 7 , - 5 , - 3 , 0 , 1 , 3 , 5 , 7 ] target = 7 return iter ( 0 , len ( list ) - 1 , 0 , list , target) if __name__ = = ‘__main__‘ : element,count = binarySearch() print "search element: %d\nsearch count:%d" % (element,count) element,count = binarySearchIte() print "search element: %d\nsearch count:%d" % (element,count)
Data Structure-Binary Search