Use of Golang sort package

Posted by avatar.alex on Sun, 03 Nov 2019 04:22:46 +0100

1. Introduction to sort package

The standard library sort package in Golang provides primitives for sorting slices and user-defined collections. Sort package provides sorting support for built-in type slices, such as [] int slice, [] float64 slice and [] string slice. If you need to sort the custom struct type slices, you need to implement three methods of interface sort.Interface.

type Interface interface {
    // Len is the total number of elements in the collection
    Len() int
	
    // Less returns whether the element with index i should precede the element with index j.
    Less(i, j int) bool
	
    // Swap elements indexed i and j
    Swap(i, j int)
}

2. Built in type slice sorting

//Integer sorting
ages := []int{2, 1, 5, 66, 55, 23}
sort.Ints(ages)
fmt.Println(ages)

//Floating point sorting
float64Slice :=[]float64{1.1, 4.4, 2.2, 3.3, 5.5, 6.6}
sort.Float64s(float64Slice)
fmt.Println(float64Slice)

//String sort
names := []string{"Hello", "World", "private", "folders", "Users", "workspace"}
sort.Strings(names)
fmt.Println(value)

Output results:

[1 2 5 23 55 66]
[1.1 2.2 3.3 4.4 5.5 6.6]
[Hello Users World folders private workspace]

If you want to sort in descending order, you need to use the sort.Reverse() function. Take [] int section as an example.

ages := []int{2, 1, 5, 66, 55, 23}
sort.Sort(sort.Reverse(sort.IntSlice(ages)))
fmt.Println(ages)

Output results:

[66 55 23 5 2 1]

3. Sorting of custom struct type slices

Sort according to the fields bIsBefore and Age in the custom struct Person. The example code is as follows:

package main

import (
    "fmt"
    "sort"
)

type Person struct {
    Name string
    Age  int 
    bIsBefore bool
}

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

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { 
        if a[i].bIsBefore {
                return true
        }   
        if a[j].bIsBefore {
                return false
        }   
        return a[i].Age > a[j].Age 
}

func main() {
    people := []Person{
        {"Bob", 31, true},
        {"John", 42, false},
        {"Michael", 17, false},
        {"Jenny", 42, false},
        {"Dable", 42, false},
        {"Dongdong", 25, false},
        {"Tommy", 42, false},
    }   

    fmt.Println(people)
    sort.Sort(ByAge(people))
    fmt.Println(people)
}

Output results:

[{John 42 false} {Dable 42 false} {Michael 17 false} {Jenny 42 false} {King 13 false} {Tommy 50 false} {Bob 31 true}]
[{Bob 31 true} {Tommy 50 false} {Dable 42 false} {Jenny 42 false} {John 42 false} {Michael 17 false} {King 13 false}]

From the sorting results, we can see that by sort.Sort(), John was in front of the equal Dable and Jenny, and appeared after the same Dable and Jenny. It can be seen that sort.Sort() is an unstable sort. If you want to achieve stable sorting, use sort.Stable() to sort as follows:

[{John 42 false} {Dable 42 false} {Michael 17 false} {Jenny 42 false} {King 13 false} {Tommy 50 false} {Bob 31 true}]
[{Bob 31 true} {Tommy 50 false} {John 42 false} {Dable 42 false} {Jenny 42 false} {Michael 17 false} {King 13 false}]

Reference

[1]Package sort

Topics: less