Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the indices of the array after sorting in golang

Tags:

sorting

go

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

like image 598
Wyatt Avatar asked Jun 30 '15 14:06

Wyatt


People also ask

How do you sort an array by indices?

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.

What is sorted index?

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.

Can you sort array while maintaining index?

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.

How sort Slice works in Golang?

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.


1 Answers

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]
}
like image 170
Ainar-G Avatar answered Nov 15 '22 15:11

Ainar-G