二分查找 golang

type binarySearch struct {
    keys []byte
    values []int
}
func (this *binarySearch)put(key byte,value int){
    index,isFind :=this.rank(key)
    if isFind{
        this.values[index] = value
        return
    }

    rear:=append([]byte{},this.keys[index:]...)
    rear2:=append([]int{},this.values[index:]...)
    this.keys = append(append(this.keys[:index],key),rear...)
    this.values = append(append(this.values[:index],value),rear2...)

    return
}
func (this *binarySearch)get(key byte)(int,bool){
    index,isFind :=this.rank(key)
    if !isFind{
        return 0,false
    }
    return this.values[index],true

}
func (this *binarySearch)rank(key byte)(int,bool){

    if len(this.keys) == 0{
        return 0,false
    }
    start := 0
    end := len(this.keys)-1

    for{
        if start==end{
            if key == this.keys[(start+end)/2]{
                return start,true
            }
            return start+1,false
        }
        if key > this.keys[(start+end)/2]{

            start = (start+end)/2+1
        }else if key < this.keys[(start+end)/2]{
            end = (start+end)/2-1
        }else{
            return (start+end)/2,true
        }
    }
    return start,false
}

func main(){
    var BSST binarySearch
    BSST.put('a',15)
    //fmt.Println(BSST.keys)
    BSST.put('b',17)
    BSST.put('c',17)
    BSST.put('d',19)
    BSST.put('w',21)
    BSST.put('c',19)
    fmt.Println(BSST.get('g'))
    fmt.Println(BSST.get('c'))
    fmt.Println(BSST.keys)
    fmt.Println(BSST.values)


}

你可能感兴趣的:(二分查找 golang)