mirror of
https://github.com/duanhf2012/origin.git
synced 2026-02-04 06:54:45 +08:00
新增算法模块
This commit is contained in:
40
util/algorithms/BiSearch.go
Normal file
40
util/algorithms/BiSearch.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package algorithms
|
||||||
|
|
||||||
|
|
||||||
|
type NumberType interface {
|
||||||
|
int | int8 | int16 | int32 | int64 | string | float32 | float64 | uint | uint8 | uint16 | uint32 | uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
type Element[ValueType NumberType] interface {
|
||||||
|
GetValue() ValueType
|
||||||
|
}
|
||||||
|
|
||||||
|
//BiSearch 二分查找,切片必需有序号。matchUp表示是否向上范围查找。比如:数列10 20 30 ,当value传入25时,返回结果是2,表示落到3的范围
|
||||||
|
func BiSearch[ValueType NumberType, T Element[ValueType]](sElement []T, value ValueType, matchUp bool) int {
|
||||||
|
low, high := 0, len(sElement)-1
|
||||||
|
if high == -1 {
|
||||||
|
return -1
|
||||||
|
}
|
||||||
|
|
||||||
|
var mid int
|
||||||
|
for low <= high {
|
||||||
|
mid = low + (high-low)>>1
|
||||||
|
if sElement[mid].GetValue() > value {
|
||||||
|
high = mid - 1
|
||||||
|
} else if sElement[mid].GetValue() < value {
|
||||||
|
low = mid + 1
|
||||||
|
} else {
|
||||||
|
return mid
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if matchUp == true {
|
||||||
|
if (sElement[mid].GetValue()) < value &&
|
||||||
|
(mid+1 < len(sElement)-1) {
|
||||||
|
return mid + 1
|
||||||
|
}
|
||||||
|
return mid
|
||||||
|
}
|
||||||
|
|
||||||
|
return -1
|
||||||
|
}
|
||||||
28
util/algorithms/BiSearch_test.go
Normal file
28
util/algorithms/BiSearch_test.go
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
package algorithms
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MyElement struct {
|
||||||
|
Score int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s MyElement) GetValue() int {
|
||||||
|
return s.Score
|
||||||
|
}
|
||||||
|
|
||||||
|
func Test_BiSearch(t *testing.T){
|
||||||
|
var schedulePoolCfgList []MyElement = []MyElement{MyElement{10}, MyElement{12}, MyElement{14}, MyElement{16}} //
|
||||||
|
index := BiSearch[int, MyElement](schedulePoolCfgList, 9, true)
|
||||||
|
index = BiSearch[int, MyElement](schedulePoolCfgList, 10, true)
|
||||||
|
index = BiSearch[int, MyElement](schedulePoolCfgList, 11, true)
|
||||||
|
index = BiSearch[int, MyElement](schedulePoolCfgList, 12, true)
|
||||||
|
index = BiSearch[int, MyElement](schedulePoolCfgList, 13, true)
|
||||||
|
index = BiSearch[int, MyElement](schedulePoolCfgList, 14, true)
|
||||||
|
index = BiSearch[int, MyElement](schedulePoolCfgList, 15, true)
|
||||||
|
index = BiSearch[int, MyElement](schedulePoolCfgList, 16, true)
|
||||||
|
index = BiSearch[int, MyElement](schedulePoolCfgList, 17, true)
|
||||||
|
fmt.Println(index)
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user