This commit is contained in:
2025-02-06 11:14:33 +08:00
commit 07847a2d9e
535 changed files with 65131 additions and 0 deletions

29
pkg/utility/search.go Normal file
View 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
}