Skip to content

Instantly share code, notes, and snippets.

@ericjster
Created May 16, 2019 10:22
Show Gist options
  • Save ericjster/1f44fda536728cbbfddd3df0e2a613d8 to your computer and use it in GitHub Desktop.
Save ericjster/1f44fda536728cbbfddd3df0e2a613d8 to your computer and use it in GitHub Desktop.
golang argsort
// https://play.golang.org/p/A3niFJ582wJ
package main
import (
"fmt"
"sort"
)
func main() {
fmt.Println("Hello, playground")
example := []float64{1, 25, 3, 5, 4}
fmt.Println("pre :", example)
ia := ArgsortNew(example)
fmt.Println("post:", example)
fmt.Println("ia :", ia)
sortedExample := []float64{}
for i := range ia {
sortedExample = append(sortedExample, example[ia[i]])
}
fmt.Println("sortedExample:", sortedExample)
}
//----------
// argsort, like in Numpy, it returns an array of indexes into an array. Note
// that the gonum version of argsort reorders the original array and returns
// indexes to reconstruct the original order.
type argsort struct {
s []float64 // Points to orignal array but does NOT alter it.
inds []int // Indexes to be returned.
}
func (a argsort) Len() int {
return len(a.s)
}
func (a argsort) Less(i, j int) bool {
return a.s[a.inds[i]] < a.s[a.inds[j]]
}
func (a argsort) Swap(i, j int) {
a.inds[i], a.inds[j] = a.inds[j], a.inds[i]
}
// ArgsortNew allocates and returns an array of indexes into the source float
// array.
func ArgsortNew(src []float64) []int {
inds := make([]int, len(src))
for i := range src {
inds[i] = i
}
Argsort(src, inds)
return inds
}
// Argsort alters a caller-allocated array of indexes into the source float
// array. The indexes must already have values 0...n-1.
func Argsort(src []float64, inds []int) {
if len(src) != len(inds) {
panic("floats: length of inds does not match length of slice")
}
a := argsort{s: src, inds: inds}
sort.Sort(a)
}
@mkmik
Copy link

mkmik commented Dec 18, 2019

if you need a package that does it with any sort.Interface, here is one: https://godoc.org/github.com/mkmik/argsort

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment