Python 3 教程 Python 线性查找

holland · 2022-03-15 13:58:48 · 热度: 6

线性查找指按一定的顺序检查数组中每一个元素,直到找到所要寻找的特定值为止。

实例

def search(arr, n, x): for i in range (0, n): if (arr[i] == x): return i return -1 # 在数组 arr 中查找字符 D arr = [ 'A', 'B', 'C', 'D', 'E' ] x = 'D' n = len(arr) result = search(arr, n, x) if(result == -1): print("元素不在数组中") else: print("元素在数组中的索引为", result)

执行以上代码输出结果为:

元素在数组中的索引为 3

查看更多 Python 实例

猜你喜欢:
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册