Go: How to sort in Go

All algorithms in the Go sort package make O(n log n) comparisons in the worst case, where n is the number of elements to be sorted.

Sort a slice of ints, float64s or strings

Use one of the functions

s := []int{4, 2, 3, 1}
sort.Ints(s)
fmt.Println(s) // [1 2 3 4]

Sort with custom compare function

  • Use the function sort.Slice. It sorts a slice using a provided less(i, j int) bool function.
  • To sort the slice while keeping the original order of equal elements, use sort.SliceStable instead.
family := []struct {
	Name string
	Age  int
}{
	{"Alice", 23},
	{"David", 2},
	{"Eve", 2},
	{"Bob", 25},
}

// Sort by age, keeping original order or equal elements.
sort.SliceStable(family, func(i, j int) bool {
	return family[i].Age < family[j].Age
})
fmt.Println(family) // [{David 2} {Eve 2} {Alice 23} {Bob 25}]

Sort custom data structures

type Interface interface {
        // Len is the number of elements in the collection.
        Len() int
        // Less reports whether the element with
        // index i should sort before the element with index j.
        Less(i, j int) bool
        // Swap swaps the elements with indexes i and j.
        Swap(i, j int)
}

Here is an example:

type Person struct {
	Name string
	Age  int
}

// ByAge implements sort.Interface based on the Age field.
type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
	family := []Person{
		{"Alice", 23},
		{"Eve", 2},
		{"Bob", 25},
	}
	sort.Sort(ByAge(family))
	fmt.Println(family) // [{Eve 2} {Alice 23} {Bob 25}]
}

Comments

Be the first to comment!