zoukankan      html  css  js  c++  java
  • Python-二分法查找

    #!/usr/bin/env python
    #_*_ coding:utf-8 _*_  
    #encoding=utf-8
    #function:实现二分法查找的方法
    #created by xkq
    #date: 2018
    def BinarySearch_1(data_source,find):#方法一
        mid = int(len(data_source) / 2)
        if len(data_source)>1:
            if data_source[mid]>find:
                #print(data_source[:mid])
                #print("on the left of %s"%data_source[mid])
                BinarySearch_1(data_source[:mid],find)
            elif data_source[mid]<find:
                #print(data_source[mid:])
                #print("on the right of %s" % data_source[mid])
                BinarySearch_1(data_source[mid:], find)
            else:
                print("find:%s"%data_source[mid])
        elif len(data_source)==1:
            if data_source[mid]==find:
                print("find:%s" % data_source[mid])
            else:
                print("no find")
    
    def BinarySearch(data_source,find):#方法二
        low=0#列表起始位置
        height=len(data_source)-1#列表结束位置
        while low<=height:
            mid=int((low+height)/2)#列表中间位置
            if data_source[mid]<find:
                low=mid+1
            elif data_source[mid]>find:
                height=mid-1
            else:
                print( "find %s in list[%s]"%(data_source[mid],mid))#返回查找到的数和位置
                return
        else:
            print("no find %s"%find)
    if __name__=='__main__':
        data=list(range(1,30000000,3))#创建数字列表
        BinarySearch_1(data,91)#方法一调用
        BinarySearch(data,91)#方法二调用
    

      

  • 相关阅读:
    JavaScript 19 数组(二)
    JavaScript 19 数组(一)
    JavaScript 18 字符串(三)
    JavaScript 18 字符串(二)
    JavaScript 18 字符串(一)
    History 5 : Silk Roads / Mongols / Ottoman and Mughal Empires
    History : Pictures of History
    001 markdown基本语法
    c#知识结构图
    c#知识结构图
  • 原文地址:https://www.cnblogs.com/qqran/p/8799738.html
Copyright © 2011-2022 走看看