說(shuō)明
線性搜索是指從數(shù)組0下標(biāo)開(kāi)始荚守,依次序搜索對(duì)比的搜索方式珍德。
代碼
package arithmetic
import (
"math"
)
//SearchLinearRtFirst 線性搜索返回第一個(gè)結(jié)果 面向算法
func SearchLinearRtFirst(element interface{}, slice []interface{},
funcCondition func(interface{}, interface{}) bool) (int, bool) {
for i, v := range slice {
if funcCondition(v, element) {
return i, true
}
}
return len(slice), false
}
//InterfaceSearch 搜索接口
type InterfaceSearch interface {
Len() int
Condition(i int, element interface{}) bool
GetElement(i int) interface{}
}
//SearchLinearRtFirstOop 線性搜索返回第一個(gè)結(jié)果 面向?qū)ο?func SearchLinearRtFirstOop(element interface{}, slice InterfaceSearch) (int, bool) {
for i := 0; i < slice.Len(); i++ {
if slice.Condition(i, element) {
return i, true
}
}
return slice.Len(), false
}
代碼說(shuō)明
面向算法:線性遍歷數(shù)組练般,通過(guò)閉包傳入的判斷條件判斷兩個(gè)元素是否相等,若相等返回元素所在數(shù)組下標(biāo)锈候,以及true 薄料。若未搜索到數(shù)據(jù)則返回?cái)?shù)組長(zhǎng)度,以及false泵琳。
面向?qū)ο螅航Y(jié)構(gòu)體通過(guò)實(shí)現(xiàn)接口摄职,取代原本閉包傳入的方式。
兩種方式各有優(yōu)缺點(diǎn)获列。主要在調(diào)用時(shí)谷市,面向算法因?yàn)镚o語(yǔ)言的特性問(wèn)題,需要將結(jié)構(gòu)數(shù)組轉(zhuǎn)換成通用的[]interface{}击孩,此部分比較耗時(shí)迫悠。兩種代碼實(shí)現(xiàn)方式都可用于自身結(jié)構(gòu)數(shù)組。其他編程語(yǔ)言情況有所不同巩梢。具體調(diào)用方式見(jiàn)下文及皂。
測(cè)試代碼
package main
import (
"AZframework/arithmetic"
"fmt"
)
//IntSlice []int
type IntSlice []int
//Len 搜索對(duì)比接口
func (s IntSlice) Len() int { return len(s) }
//Condition 搜索對(duì)比接口
func (s IntSlice) Condition(i int, element interface{}) bool {
if s[i] == element.(int) {
return true
}
return false
}
//GetElement 搜索對(duì)比接口
func (s IntSlice) GetElement(i int) interface{} { return s[i] }
func main() {
var intB = 1
var sliceC = IntSlice{2, 3, 1, 4, 1}
//數(shù)組轉(zhuǎn)換
var interSlice = make([]interface{}, len(sliceC))
for i, d := range sliceC {
interSlice[i] = d
}
var x, y = arithmetic.SearchLinearRtFirst(intB, interSlice, func(a interface{}, b interface{}) bool {
if a == b {
return true
}
return false
})
fmt.Printf("SearchLinearRtFirst %t %d\n", y, x)
var x2, y2 = arithmetic.SearchLinearRtFirstOop(intB, sliceC)
fmt.Printf("SearchLinearRtFirstOop %t %d\n", y2, x2)
}
日志輸出
SearchLinearRtFirst true 2
SearchLinearRtFirstOop true 2