美文网首页
线性搜索算法 Go

线性搜索算法 Go

作者: AusenZ | 来源:发表于2018-07-30 17:54 被阅读0次

    说明

    线性搜索是指从数组0下标开始,依次序搜索对比的搜索方式。

    代码

    package arithmetic
    
    import (
        "math"
    )
    
    //SearchLinearRtFirst 线性搜索返回第一个结果 面向算法
    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 线性搜索返回第一个结果 面向对象
    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
    }
    

    代码说明

    面向算法:线性遍历数组,通过闭包传入的判断条件判断两个元素是否相等,若相等返回元素所在数组下标,以及true 。若未搜索到数据则返回数组长度,以及false。

    面向对象:结构体通过实现接口,取代原本闭包传入的方式。

    两种方式各有优缺点。主要在调用时,面向算法因为Go语言的特性问题,需要将结构数组转换成通用的[]interface{},此部分比较耗时。两种代码实现方式都可用于自身结构数组。其他编程语言情况有所不同。具体调用方式见下文。

    测试代码

    package main
    
    import (
        "AZframework/arithmetic"
        "fmt"
    )
    
    //IntSlice []int
    type IntSlice []int
    //Len 搜索对比接口
    func (s IntSlice) Len() int           { return len(s) }
    //Condition 搜索对比接口
    func (s IntSlice) Condition(i int, element interface{}) bool {
        if s[i] == element.(int) {
            return true
        }
        return false
    }
    //GetElement 搜索对比接口
    func (s IntSlice) GetElement(i int) interface{} { return s[i] }
    
    func main() {
        var intB = 1
        var sliceC = IntSlice{2, 3, 1, 4, 1}
        //数组转换
        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

    相关文章

      网友评论

          本文标题:线性搜索算法 Go

          本文链接:https://www.haomeiwen.com/subject/lsgfvftx.html