最近碰上了一个需求,要得到排序后的原索引序列。
我又不希望自己重新实现一快排出来,所以在接口上重新封装了一下。

package main

import (
	"fmt"
	"sort"
)

type SortIndexs struct {
	sort.IntSlice // 可以替换成其他实现了 sort.Interface 
	indexs []int
}

func (p *SortIndexs) Swap(i, j int) {
	p.IntSlice.Swap(i, j)
	p.indexs[i], p.indexs[j] = p.indexs[j], p.indexs[i]
}

func NewSortIndexs(arr []int) *SortIndexs {
	s := &SortIndexs{IntSlice: sort.IntSlice(arr), indexs: make([]int, len(arr))}
	for i := range s.indexs {
		s.indexs[i] = i   // 原有排序 indexs
	}
	return s
}

func main() {
	s := NewSortIndexs([]int{5,8,10,2,9,6})
	sort.Sort(s)
	fmt.Println(s.indexs)
	fmt.Println(s.IntSlice)
}

输出

[3 0 5 1 4 2]
[2 5 6 8 9 10]

相关文章:

  • 2022-12-23
  • 2022-01-14
  • 2021-07-11
  • 2022-02-09
  • 2022-12-23
  • 2021-12-24
  • 2021-11-17
猜你喜欢
  • 2021-11-29
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-16
  • 2022-02-15
相关资源
相似解决方案