go排序后索引

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

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]

posted @ 2017-05-13 15:11  糊塗神  阅读(498)  评论(0编辑  收藏  举报