Sorting in golang

Today I'm going to talk about sorting arrays using the sort package. There is a bit of ground work which need to be done before sorting any structs. Note that the sort package provides methods for sorting floats, ints and strings.
Lets see a quick example
package main

import (
	"fmt"
	"sort"
)

type Player struct {
	Name  string
	Score int
}

type PlayerSorter struct {
	Players []Player
}

func (s PlayerSorter) Len() int {
	return len(s.Players)
}

func (s PlayerSorter) Swap(i, j int) {
	s.Players[i], s.Players[j] = s.Players[j], s.Players[i]
}

func (s PlayerSorter) Less(i, j int) bool {
	if s.Players[i].Score < s.Players[j].Score {
		return false
	}
	return true
}

func main() {
	//Build the data to sort
	players := []Player{
		Player{"Andy", 1000},
		Player{"Bob", 2000},
		Player{"Nirandas", 4000},
		Player{"Nidheeshdas", 3000},
	}

	fmt.Println("Before sort")
	for _, p := range players {
		fmt.Println(p.Name, p.Score)
	}

	s := PlayerSorter{players}
	sort.Sort(s)

	fmt.Println("After sorting")
	for _, p := range players {
		fmt.Println(p.Name, p.Score)
	}
}
The main thing to note here is that we need a struct implementing the sort.Interface interface before we can start sorting. The interface has three methods
Len()
Return the total number of items.
Swap(i,j int)
Swap swaps the elements with indexes i and j.
Less(i,j int)bool
Less reports whether the element with index i should sort before the element with index j. Here is where you implement the item comparison.

The sort package uses these method to sort and reorder the data. Read more about sort package here.

© 2018 Nirandas Thavorath. All Rights Reserved.
Last updated at Friday July 21, 2017 11:19 PM