Go sorting, an example

I was recently trying to figure out a way to sort entries stored in a map using Golang. And then, I came across the “sort” package. It provides a Sort() function which can used to sort slices and user-defined collections.

func Sort(data Interface)

All you need is to define the functions listed under the Interface type.

Here is an example to demonstrate the same :

package main

import (
        "fmt"
        "sort"
)

type keys []int

/* Definitions for all 'Interface' functions. */
func (k keys) Len() int           { return len(k) }
func (k keys) Less(i, j int) bool { return k[i] < k[j] }
func (k keys) Swap(i, j int)      { k[i], k[j] = k[j], k[i] }

func main() {
        var (
                k keys
                i int
        )

        var varMap = map[int][]string{
                3: []string{"Harry"},
                1: []string{"Tom"},
                2: []string{"Dick"}}

        k = make(keys, 3)

        for key, _ := range varMap {
                k[i] = key
                i++
        }

        sort.Sort(k)

        for i = 0; i < len(k); i++ {
                fmt.Println(k[i], " : ", varMap[k[i]])
        }
}

Output :
>  go run sort.go 
1  :  [Tom]
2  :  [Dick]
3  :  [Harry]

Leave a Reply

Your email address will not be published. Required fields are marked *