在golang中排序后获取数组的索引 [英] Get the indices of the array after sorting in golang
问题描述
我知道我们可以使用
sort.Sort(sort.Reverse(sort.IntSlice(example)))
对数组进行排序。
例如:
例如:我得到数组的索引?
= [] int {1,25,3,5,4}
我想获得输出:1,3,5,4,2
为 游乐场: http:// play .golang.org / p / LnSLfe-fXk 。 编辑:正如DaveC在评论中提到的, y围绕 I know we can use to sort a array. But how can I get the indices of the array? e.g. I want to get the output: 1, 3, 5, 4, 2 Make a wrapper for Playground: http://play.golang.org/p/LnSLfe-fXk. EDIT: As DaveC mentioned in the comments, you can actually wrap around
这篇关于在golang中排序后获取数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! sort.IntSlice code>记住索引,并在交换值时交换它们:
$ b $ pre> type Slice struct {
pre>
sort.IntSlice
idx [] int
}
func(s Slice)Swap(i,j int){
s.IntSlice.Swap(i,j )
s.idx [i],s.idx [j] = s.idx [j],s.idx [i]
}
sort.Interface
创建任何可排序类型的数据结构:
type Slice struct {
sort.Interface
idx [] int
}
func(s Slice)Swap(i,j int){
s.Interface.Swap(i,j)
s.idx [i],s.idx [j] = s.idx [j],s.idx [i]
}
sort.Sort(sort.Reverse(sort.IntSlice(example)))
example := []int{1, 25, 3, 5, 4}
sort.IntSlice
that remembers the indexes and swaps them when it swaps the values:type Slice struct {
sort.IntSlice
idx []int
}
func (s Slice) Swap(i, j int) {
s.IntSlice.Swap(i, j)
s.idx[i], s.idx[j] = s.idx[j], s.idx[i]
}
sort.Interface
to create a data structure for any sortable type:type Slice struct {
sort.Interface
idx []int
}
func (s Slice) Swap(i, j int) {
s.Interface.Swap(i, j)
s.idx[i], s.idx[j] = s.idx[j], s.idx[i]
}