[查詢演算法]:順序查詢
阿新 • • 發佈:2022-01-10
python 和 golang 實現 linear_search
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 ####################################### */
本文來自部落格園,作者:渝北小站,轉載請註明原文連結:https://www.cnblogs.com/timgunt/p/15785915.html