ruk·si

Go
Sorting

Updated at 2014-03-07 08:44

There are native sorting functionality for strings, integers and floats. Note that sort changes the slice.

package main

import (
    "fmt"
    "sort"
)

func main() {
    strings := []string{"c", "a", "b"}
    sort.Strings(strings)
    stringsAreSorted := sort.StringsAreSorted(strings)
    fmt.Println("Strings:", strings, "are sorted:", stringsAreSorted)

    integers := []int{7, 2, 4}
    sort.Ints(integers)
    intsAreSorted := sort.IntsAreSorted(integers)
    fmt.Println("Ints: ", integers, "are sorted:", intsAreSorted)

    floats := []float64{1.23, 64.55, -0.23}
    sort.Float64s(floats)
    floatsAreSorted := sort.Float64sAreSorted(floats)
    fmt.Println("Float64s: ", floats, "are sorted:", floatsAreSorted)
}

You can specify custom sorting by implementing sort.Interface. Anything sortable must have Len(), Less() and Swap().

package main

import (
    "fmt"
    "sort"
)

type ByNameLength []string

func (self ByNameLength) Len() int {
    return len(self)
}

func (self ByNameLength) Swap(i, j int) {
    self[i], self[j] = self[j], self[i]
}

func (self ByNameLength) Less(i, j int) bool {
    return len(self[i]) < len(self[j])
}

func main() {
    fruits := []string{"peach", "strawberry", "banana", "kiwi"}

    fmt.Println(fruits)
    // => [peach strawberry banana kiwi]

    sort.Sort(ByNameLength(fruits))

    fmt.Println(fruits)
    // => [kiwi peach, banana, strawberry]
}

Sorting times can be done in a similar way.

package main

import (
    "fmt"
    "sort"
    "time"
)

// Creating a new time array type that implements `sort.Interface`.
// The new type is used to allow sorting the underlying time array.
type ByTime []time.Time

func (self ByTime) Len() int {
    return len(self)
}

func (self ByTime) Swap(i, j int) {
    self[i], self[j] = self[j], self[i]
}

func (self ByTime) Less(i, j int) bool {
    return self[i].Before(self[j])
}

func main() {
    const shortForm = "Jan/02/2006 15:04:05"
    t1, _ := time.Parse(shortForm, "Feb/02/2014 00:00:00")
    t2, _ := time.Parse(shortForm, "Feb/02/1800 00:00:00")
    t3, _ := time.Parse(shortForm, "Feb/02/1999 00:00:00")
    t4, _ := time.Parse(shortForm, "Feb/02/2014 00:11:00")
    t5, _ := time.Parse(shortForm, "Feb/02/2000 00:00:00")
    times := []time.Time{t1, t2, t3, t4, t5}

    fmt.Println("Original:")
    for _, t := range times {
        fmt.Println(t)
    }

    sort.Sort(ByTime(times))

    fmt.Println("\nSorted:")
    for _, t := range times {
        fmt.Println(t)
    }
}

Sources