package main
import (
"fmt"
)
type SortedList interface {
Len() int
Cmp(i int) int8
}
type Person struct {
age int
}
type SortedIntList []Person
func (p Person) Cmp(cmp Person) int8 {
if p.age == cmp.age {
return 0
} else if p.age > cmp.age {
return 1
} else {
return -1
}
}
func (s SortedIntList) Cmp(i int) int8 {
return s[i].Cmp(s[len(s)-1])
}
func (s SortedIntList) Len() int {
return len(s) - 1
}
func BinarySearch(list SortedList) int {
lower, higher := 0, list.Len()-1
for lower <= higher {
//防止超过int范围
mid := lower + (higher-lower)/2
cmp := list.Cmp(mid)
switch cmp {
case 0:
return mid
case 1:
higher = mid - 1
case -1:
lower = mid + 1
}
}
return -1
}
func searchInt(list []Person, target Person) int {
a := append(SortedIntList(list), target)
return BinarySearch(a)
}
func main() {
a := searchInt([]Person{{12}, {13}, {14}}, Person{14})
fmt.Println(a)
}
有疑问加站长微信联系(非本文作者)