golang: sort.Search无法找到切片中的第一个元素

huangapple go评论73阅读模式
英文:

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 (
    &quot;fmt&quot;
	&quot;sort&quot;
)

func main() {
    data := []int{1, 2, 3}
	fmt.Println(sort.Search(len(data), func(i int) bool {
    	return data[i] &lt; 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 &gt;= 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] &gt;= data[0] // You could also use 1 instead of data[0]
}))

Output: 0 as expected. Try it on Go Playground.

huangapple
  • 本文由 发表于 2015年2月5日 21:06:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/28344757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定