Python for binary search (binary query)

Source: Internet
Author: User
Two-part query algorithm

Def BinarySearch (A, target): Low     = 0    higher = Len (a)-1    while low <= High: #在其它语言中 if low + high and greater than integer maximum Value, such as 2 * * 31-1, #计算便会发生溢出, make it a negative number, and then divide by 2 when the result is still negative. In the Java language, #这个Bug导致一个ArrayIndexOutOfBoundsException异常被抛出, and in the C language, #你会得到一个无法预测的越界的数组下标. The recommended workaround is to modify the middle value of the calculation process, #方法之一是用减法而不是加法-to achieve: Mid = low + ((high-low)/2), or, #如果你想炫耀一下自己掌握的移位运算的知识, can use a faster shift operation, # In Python is mid = (low + high) >> 1,java is int mid = (low + high) >>> 1.        mid = (low + high)//2        midval = A[mid]         if Midval < target: Low            = mid + 1        elif midval > target: High            = mid-1        Else:            return mid    return-1
  • 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.