1
This commit is contained in:
29
pkg/utility/search.go
Normal file
29
pkg/utility/search.go
Normal file
@ -0,0 +1,29 @@
|
||||
package utility
|
||||
|
||||
import "sort"
|
||||
|
||||
// 二分查找(会将切片 a 排为升序)
|
||||
//
|
||||
// 找到返回 true,未找到返回 false
|
||||
func BinarySearch(a []int, x int) bool {
|
||||
if !sort.IntsAreSorted(a) {
|
||||
sort.Ints(a)
|
||||
}
|
||||
|
||||
l, r := 0, len(a)-1
|
||||
|
||||
for l <= r {
|
||||
m := (l + r) / 2
|
||||
if a[m] == x {
|
||||
return true
|
||||
}
|
||||
// x 在左边
|
||||
if x < a[m] {
|
||||
r = m - 1
|
||||
} else {
|
||||
l = m + 1
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user