Sorting 在golang中排序后获取数组的索引

Sorting 在golang中排序后获取数组的索引,sorting,go,Sorting,Go,我知道我们可以用 sort.Sort(sort.Reverse(sort.IntSlice(example))) 对数组进行排序 但是我怎样才能得到数组的索引呢 e、 g 我想得到输出:1、3、5、4、2为sort.IntSlice创建一个包装器,它记住索引并在交换值时交换它们: type Slice struct { sort.IntSlice idx []int } func (s Slice) Swap(i, j int) { s.IntSlice.Swap(i

我知道我们可以用

sort.Sort(sort.Reverse(sort.IntSlice(example)))
对数组进行排序

但是我怎样才能得到数组的索引呢

e、 g


我想得到输出:1、3、5、4、2为sort.IntSlice创建一个包装器,它记住索引并在交换值时交换它们:

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]
}
操场:

EDIT:正如DaveC在评论中提到的,您实际上可以围绕
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]
}

您也可以只获取索引并避免在适当的位置对切片进行变异,请参见

Nice!你一定会喜欢的@Ainar-G如果数据是[1.1.2]这些浮点数,该怎么办。我将IntSlice更改为Float64Slice,但它不起作用,如果您不知道什么类型的
sort.Interface
,您将有如下操作:包装任何
sort.Interface
,而不是
sort.IntSlice
。用户看到的唯一区别是方便性
New…
函数,该函数采用可变参数列表。@DaveC没有想到,谢谢。添加到我的答案中。仅供参考,您的
1,3,5,4,2
,实际上应该是
0,2,4,3,1
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]
}