栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【python&顺序查找算法、二分查找算法、二分法查找的递归解法】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【python&顺序查找算法、二分查找算法、二分法查找的递归解法】

【python&顺序查找算法、二分查找算法、二分法查找的递归解法】
    • 顺序查找算法
    • 二分查找算法
    • 二分法查找的递归解法

顺序查找算法
# 顺序查找项,并输出其索引

def sequentialSearch(list,item):
    pos = 0
    found = False
    # 按照索引持续对比查找
    while pos < len(list)  and not found:
          # 对比找到索引项
        if list[pos] == item:
            found = True
        else:
            # 否则,顺序增长 下标
            pos = pos + 1
    return found,pos

testlist = [1,2,3,4,5,6,78,54,32,11,0]
item = 11
res = sequentialSearch(testlist,item)


print("在%s中查找%s,%s,并且其索引值为:%s" %(testlist,item,res[0],res[1]))

结果:

在[1, 2, 3, 4, 5, 6, 78, 54, 32, 11, 0]中查找11,True,并且其索引值为:9

二分查找算法

# 二分法查找  binarySearch
def function(list,item):
    first = 0
    last = len(list)-1
    found = False
    while first <= last and  not found:
        midpoint = (first + last)//2
        if midpoint == item:
            found = True
        else:
            if item < list[midpoint]:
                last = midpoint - 1
            else:
                first = midpoint  + 1
       
    return found


list= [1,2,3,4,5,6,7,8,9,10,11]
print(function(list,6))


结果:

True

二分法查找的递归解法
def binarySearch(list,item):
    if len(list) == 0:
        return False
    else:
        midpoint = len(list)//2
        if list[midpoint] == item:
            return True
        else:
            if item < list[midpoint]:
                return binarySearch(list[:midpoint],item)
            else:
                return binarySearch(list[midpoint+1:],item)


list= [1,2,3,4,5,6,7,8,9,10,11,15]

print(binarySearch(list,5))



结果:

True

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/339251.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号