Python for two-point lookup

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.