[查找算法]:顺序查找

python 和 golang 实现 linear_search

顺序查找:从列表的第一个元素开始,按照顺序对列表进行搜索,找到待查找的元素就返回其下标,找不到就返回None或-1

> python

def linear_search(data_list,value):
    for i in range(0,len(data_list),1):
        # 下标从 0 取到 len(data_list)-1
        if data_list[i] == value:
            return i
    # 遍历完data_list仍然没有查到
    return None


temp = [273,21,31,7,9,0,93,-12,3]
print("index=",linear_search(temp,-12))

# [运行结果如下]:#####################
"""
index= 7
"""
# ####################################

> golang

package main

import (
	"fmt"
	"os/exec"
)

func LinearSearch(DataList []int, value int) (int, error) {
	for i, _ := range DataList {
		if DataList[i] == value {
			return i, nil
		}
	}
	return -1, exec.ErrNotFound
}

func main() {

	temp := [...]int{273, 21, 31, 7, 9, 0, 93, -12, 3}

	// 使用切片在函数间进行传递,可以避免指明数组长度的繁琐操作
	num, _ := LinearSearch(temp[:], -12)

	fmt.Printf("index=%d", num)
}


/* [运行结果如下]:########################
index=7
####################################### */

posted @ 2022-01-10 20:58  渝北小站  阅读(64)  评论(0)    收藏  举报