Python implements binary search and python Binary Search
Binary Search Algorithm: Simply put, an array is sorted first, for example, in ascending order. When a data, such as target, when searching for the position of the target in the array, You can first find the number array [middle] in the middle of the array and compare it with the target. When it is smaller than the target, the target must be on the right of the array, on the contrary, the target is on the left side of the array. For example, if it is smaller than the target, you can compare the number of [middle + 1, end] Next time. continue to use the bipartite method to split it into two parts, until the number of target values is found, or the array is completely traversed (the target is not in the array)
Advantage: high efficiency, time complexity is O (logN );
Disadvantage: data is ordered and stored in sequence.
Python code implementation is as follows:
#!/usr/bin/python env# -*- coding:utf-8 -*-def half_search(array,target): low = 0 high = len(array) - 1 while low < high: mid = (low + high)/2 if array[mid] > target: high = mid - 1 elif array[mid] < target: low = mid + 1 elif array[mid] == target: print 'I find it! It is in the position of:',mid return mid else: print "please contact the coder!" return -1if __name__ == "__main__": array = [1, 2, 2, 4, 4, 5]
The running result is as follows:
I find it! It is in the position of: 44-1I find it! It is in the position of: 00-1
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.