Principle
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. Therefore, the binary lookup method is suitable for an ordered list that does not change frequently and finds frequent. First, suppose that the elements in the table are arranged in ascending order, comparing the keywords in the middle position of the table with the lookup keywords, and if they are equal, the lookup succeeds; otherwise, the table is divided into the front and the last two sub-tables with the intermediate positional records, and if the middle position record keyword is greater than the Find keyword, the previous child Otherwise, find the latter child table further. Repeat the process until you find a record that satisfies the criteria, make the lookup successful, or until the child table does not exist, the lookup is unsuccessful at this time.
Realize
"""1. 二分查找是有条件的,首先是有序,其次因为二分查找操作的是下标,所以要求是顺序表2. 最优时间复杂度:O(1)3. 最坏时间复杂度:O(logn)"""# def binary_chop(alist, data):# """# 递归解决二分查找# :param alist:# :return:# """# n = len(alist)# if n < 1:# return False# mid = n // 2# if alist[mid] > data:# return binary_chop(alist[0:mid], data)# elif alist[mid] < data:# return binary_chop(alist[mid+1:], data)# else:# return Truedef binary_chop(alist, data): """ 非递归解决二分查找 :param alist: :return: """ n = len(alist) first = 0 last = n - 1 while first <= last: mid = (last + first) // 2 if alist[mid] > data: last = mid - 1 elif alist[mid] < data: first = mid + 1 else: return True return Falseif __name__ == '__main__': lis = [2,4, 5, 12, 14, 23] if binary_chop(lis, 14): print('ok')
Python for two-point lookup