Files
exchange_go/pkg/utility/search.go
2025-02-06 11:14:33 +08:00

30 lines
403 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}