1、算法介绍
(1)遍历序列与查找值比较,相等返回所在下标
(2)未找到返回-1
2、代码实现
2.1、golang
package main import ( "fmt" ) func main() { slice := []int{5, 3, 12, 54, 23, 12, 6, 9, 19} key := 54 index := SearchSequential(slice, key) if index == -1 { fmt.Printf("%v不存在元素%v ", slice, key) } else { fmt.Printf("%v位于%v下标为%v的位置。 ", key, slice, index) } } //顺序查找 func SearchSequential(slice []int, key int) int { n := len(slice) for i := 0; i < n; i++ { if slice[i] == key { return i } } return -1 }
2.2、python3
# 1、顺序查找 def search_sequential(arr, key): n = len(arr) for i in range(n): if arr[i] == key: return i return -1 if __name__ == '__main__': arr = [5, 3, 12, 54, 23, 12, 6, 9, 19] key = 54 index = search_sequential(arr, key) if index == -1: print("%s不存在元素%s。" % (arr, key)) else: print("%s位于%s下标为%s的位置。" % (key, arr, index))
vscode使用run code若有中文乱码解决方式:
"code-runner.executorMap": { //... "python": "set PYTHONIOENCODING=utf8 && python -u", //... }