Skip to content

Instantly share code, notes, and snippets.

@dimitrilw
Last active August 9, 2023 12:14
Show Gist options
  • Save dimitrilw/4eeac75bcf02d62e2b6c1e6b7594a767 to your computer and use it in GitHub Desktop.
Save dimitrilw/4eeac75bcf02d62e2b6c1e6b7594a767 to your computer and use it in GitHub Desktop.
Go (golang) custom sort
package main
import (
"fmt"
"sort"
)
// Slices implements the Go standard lib's Sort interface
// by having Len, Less, and Swap methods.
// This particular demo implementation sorts multiple slices,
// keeping all ints in the same relative positions, but sorted
// based on the values of the first slice in the list of slices.
type Slices [][]int
func (s Slices) Len() int { return len(s[0]) }
func (s Slices) Less(i, j int) bool { return s[0][i] < s[0][j] }
func (s Slices) Swap(i, j int) {
for sub := range s {
s[sub][i], s[sub][j] = s[sub][j], s[sub][i]
}
}
func main() {
// for demo purposes, note that all ints in same original position have same second digit
a := []int{22, 44, 11, 33}
b := []int{52, 14, 91, 23}
c := []int{92, 84, 71, 63}
d := []int{12, 24, 31, 43}
sort.Sort(Slices{a, b, c, d})
fmt.Println("a", a)
fmt.Println("b", b)
fmt.Println("c", c)
fmt.Println("d", d)
}
/* output:
a [11 22 33 44]
b [91 52 23 14]
c [71 92 63 84]
d [31 12 43 24]
*/
// note that sorted output still has all nums in same relative position as their corresponding
// "slice a" num; i.e., all second-digit-is-1 are first; all second-digit-is-2 are second, etc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment