英文:
golang: sort.Search can't find first element in a slice
问题
我已经写了一些代码,使用sort.Search来查找已排序切片中元素的位置,但它无法正确地获取第一个元素的位置。
package main
import (
"fmt"
"sort"
)
func main() {
data := []int{1, 2, 3}
fmt.Println(sort.Search(len(data), func(i int) bool {
return data[i] < 2 // or data[i] == 1
}))
}
标准输出始终为3,而不是0。
这是一个错误吗?还是我弄错了?
谢谢。
英文:
I have write some code to find element position in sorted slice use sort.Search, but it can't correctly get the right position of first element.
package main
import (
"fmt"
"sort"
)
func main() {
data := []int{1, 2, 3}
fmt.Println(sort.Search(len(data), func(i int) bool {
return data[i] < 2 // or data[i] == 1
}))
}
The standard output is always 3 rather than 0.
Is it a bug? Or am i wrong?
Thanks.
答案1
得分: 4
如果你想搜索第一个元素,那么在你的比较函数中,你应该将第i
个元素与第一个元素data[0]
(或值1
)进行比较。
由于你的切片是按升序排序的,所以在比较时你必须使用>=
运算符,因为sort.Search()
函数返回在[0, n)
范围内使得f(i)
为true
的最小索引i
。
data := []int{1, 2, 3}
fmt.Println(sort.Search(len(data), func(i int) bool {
return data[i] >= data[0] // 你也可以使用1代替data[0]
}))
输出结果应为0
,与预期相符。你可以在Go Playground上尝试运行。
英文:
If you want to search for the first element, then in your comparator function you should compare the i
<sup>th</sup> element to the first which is data[0]
(or the value which is 1
).
And since your slice is sorted in ascending order, you have to use the >=
operator for comparision because sort.Search()
returns the smallest index i
in [0, n)
at which f(i)
is true
.
data := []int{1, 2, 3}
fmt.Println(sort.Search(len(data), func(i int) bool {
return data[i] >= data[0] // You could also use 1 instead of data[0]
}))
Output: 0
as expected. Try it on Go Playground.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论