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
Approach: Create an array of indices and store 0 to n-1 (n is the size of the given array). Now sort the array by overriding the Comparator in which you will compare the elements of the given array for indices array.
Sorting and indexing are two different methods for sequentially ordering data in tables. Some Analytics commands require that the input is first sorted or indexed. Ordering data can also be a useful analytical operation in itself, bringing patterns and anomalies into focus.
Solution to Preserve indices while sorting arrayIn this Comparator, we preserve the actual array which is to be sorted. Also, if you notice, the compare method compares the values of the actual array based on the indices supplied to it. The key here is to supply the indices and not the actual values to be sorted.
In Go language, you can sort a slice with the help of Slice() function. This function sorts the specified slice given the provided less function. The result of this function is not stable. So for stable sort, you can use SliceStable.
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]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With