Basic Algorithm---binary search

Source: Internet
Author: User

Two-point Search

二分查找原理:从有序列表的候选区data[0:n]开始,通过对待查找的值与候选区中间值的比较,可以使候选区减少一半。二分查找:在一个数组内,找到中间值,判断要找的值和中间值大小的比较。如果中间值大一些,则在中间值的左侧区域继续按照上述方式查找。如果中间值小一些,则在中间值的右侧区域继续按照上述方式查找,直到找到我们希望的数字。
def Search(ListA,val):    #low 和high代表下标 最小下标,最大下标    low=0    high=len(ListA)-1    while low <=high:# 只有当low小于High的时候证明中间有数        mid=(low+high)//2        if ListA[mid]==val:            return(‘这个数在数组中的下标为:%d‘ % (mid)) #返回他的下标        elif ListA[mid]>val:            high=mid-1        else:            low=mid+1    else:        return(‘没有找到该值‘)        # return null证明没有找到ListA = list(range(100))val=input(‘输入你要查找的值:‘)val=int(val)print(Search(ListA,val ))

Basic Algorithm---binary search

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.