查找算法-顺序查找

1.查找算法:从n个元素中查找x值是否存在。

2.顺序查找:重头到尾逐个查找。

3.顺序查找的情况:

(1)第一次项找到

(2)比较n次未找到

(3)比较n/2次

4.1在列表中顺序查找特定值x。

python 复制代码
def sequential_search(lst, target):
    pos = 0  # 初始位置

    while pos<len(lst):
        if lst[pos] == target:
            return pos
        else:
            pos = pos+1
    return -1

def main():
    testlist = [1,3,6,8,5,7,9]
    print( sequential_search(testlist,10))
    print(f'索引位置:{sequential_search(testlist,3)}')

if __name__ == '__main__':
    main()

4.2在列表中顺序查找最大值和最小值。

python 复制代码
def max_search(lst):
    max_num = lst[0]
    for target in lst:
        if target>max_num:
            max_num = target
    return max_num

def min_search(lst):
	min_num = lst[0]
	for target in lst:
		if target<min_num:
			min_num = target
	return min_num
	
def main():
	testlist = [1,3,5,2,4,6,8,7,9]
	print(f'最大值:{max_search(testlist)}')
	print(f'最小值:{min_search(testlist)}')
	
if __name__ == '__main__':
	main()
		
相关推荐
学究天人9 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷2)
算法·数学建模·动态规划·图论·抽象代数·拓扑学
Java面试题总结9 小时前
Python 开发技巧 · 高级装饰器 —— 从基础到工业级实战
开发语言·python
纸小铭9 小时前
[MAF预定义ChatClient中间件-01]LoggingChatClient——在调用LLM前后输出日志
python·中间件·flask
aiqianji9 小时前
有哪些支持长文的AI生成短篇小说软件?
人工智能·python
玛卡巴卡ldf9 小时前
【LeetCode 手撕算法】(细节知识点总结)
java·数据结构·算法·leetcode·力扣
狗都不学爬虫_9 小时前
AI逆向 - 某定制瑞树6纯算(ck-header-params后缀)
爬虫·python·网络爬虫
三十岁老牛再出发9 小时前
07.08.&07.09.每日总结
c语言·python
齐 飞10 小时前
Python常用语法总结
python
wanzehongsheng10 小时前
零碳产业园光伏园区光伏电站追踪对比固定:发电增益技术边界分析
算法·光伏发电·光伏·零碳园区·太阳能追光·低碳环保·追踪电站
齐 飞10 小时前
LangGraph快速入门-03节点与边
python·langchain