Sort an array of strings by length

This Go example program illustrates sorting strings by length.

package main

import (
        "fmt"
        "sort"
)

type Animals []string

func (a Animals) Len() int {
        return len(a)
}

func (a Animals) Swap(i, j int) {
        a[i], a[j] = a[j], a[i]
}

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

func main() {
        test := []string{
                "puppy",
                "kitten",
                "duckling",
                "gosling",
                "piglet",
                "calf",
        }
        sort.Sort(Animals(test))
        for _, j := range (test) {
                fmt.Println (j)
        }
}

(download)


Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer