TheDeveloperBlog.com


Golang Sort Slices: Interface

Sort. Data often comes with no order. It is unordered. It is unorganized. Computer algorithms reorder elements to make them sequential.


With sort, a package, we gain many methods for reordering data. We can sort strings alphabetically with Strings(). For complex needs, we can use Sort and define an interface.


Strings. This method implements an ascending (low to high, alphabetical) sort of strings. So they go from A to Z. We must add the "sort" package to our import block.

In-place: The Strings method operates in-place. So we do not need to assign anything to it—it modifies the slice.

Slice: The Strings method, as well as other methods in "sort," all operate on slices. This is the standard Go approach.

Result: The strings are sorted alphabetically—so "bird" comes first and "zebra" last.

Based on:

Golang 1.4

Golang program that uses sort, Strings method

package main

import (
    "fmt"
    "sort"
)

func main() {
    animals := []string{"cat", "bird", "zebra", "fox"}

    // Sort strings.
    sort.Strings(animals)

    // Print results.
    fmt.Println(animals)
}

Output

[bird cat fox zebra]

Sort strings by length. Here we specify how elements in a slice are sorted. We use the "type" keyword to create a type. We implement the sort.Interface on our ByLen type.

Len: This method is required by sort.Interface. It is used by the sort.Sort func.

Less: This compares two elements of the type. Here we use custom code to compare the lengths of two elements.

Swap: This is used by the sorting algorithm to swap two elements in the collection.

Result: The program sorts the strings by their lengths, from shortest to longest. They are not alphabetized.

Golang program that sorts strings by length

package main

import (
    "fmt"
    "sort"
)

// Implement length-based sort with ByLen type.
type ByLen []string
func (a ByLen) Len() int           { return len(a) }
func (a ByLen) Less(i, j int) bool { return len(a[i]) < len(a[j]) }
func (a ByLen) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

func main() {
    // These elements are not sorted.
    elements := []string{"ruby", "python", "java", "go"}

    // Sort the elements by length.
    sort.Sort(ByLen(elements))

    // Print results.
    fmt.Println(elements)
}

Output

[go ruby java python]

Important. Sorting is an important problem in computer languages. In Go we can use funcs like Strings() to sort simple collections.


With the sort Interface, and its funcs Len, Less and Swap, we can sort elements in more complex ways. Sorting in Go operates on slices.