在golang中排序后获取数组的索引 [英] Get the indices of the array after sorting in golang

查看:235
本文介绍了在golang中排序后获取数组的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以使用

  sort.Sort(sort.Reverse(sort.IntSlice(example)))

对数组进行排序。

例如:

 例如:我得到数组的索引?



= [] int {1,25,3,5,4}

我想获得输出:1,3,5,4,2

解决方案

sort.IntSlice code>记住索引,并在交换值时交换它们:
$ b $ pre> 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]
}
pre>

游乐场: http:// play .golang.org / p / LnSLfe-fXk



编辑:正如DaveC在评论中提到的, y围绕 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]
}


I know we can use

sort.Sort(sort.Reverse(sort.IntSlice(example)))

to sort a array.

But how can I get the indices of the array?

e.g.

example := []int{1, 25, 3, 5, 4}

I want to get the output: 1, 3, 5, 4, 2

解决方案

Make a wrapper for 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]
}

Playground: http://play.golang.org/p/LnSLfe-fXk.

EDIT: As DaveC mentioned in the comments, you can actually wrap around 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]
}

这篇关于在golang中排序后获取数组的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆