Sort in Go

Sort a slice of ints, float64s or strings

μ•„λž˜ 쀑 ν•˜λ‚˜λ₯Ό μ‚¬μš©ν•œλ‹€.

  • sort.Ints

  • sort.Float64s

  • sort.Strings

import (
    "fmt"
    "sort"
)

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

Sort with custom comparator

  • Use the function sort.Slice. 이 ν•¨μˆ˜λŠ” μ •λ ¬ν•˜λŠ”λ° less(i, j int) bool 을 μ‚¬μš©ν•œλ‹€.

  • λ§Œμ•½ μ›λž˜ μˆœμ„œλ₯Ό μ§€ν‚€λ©΄μ„œ 정렬을 ν•˜κ³  μ‹Άλ‹€λ©΄ sort.SliceStable을 μ‚¬μš©ν•΄μ•Ό ν•œλ‹€.

//func Slice(x any, less func(i, j int) bool)
import (
	"fmt"
	"sort"
)

func main() {
	people := []struct {
		Name string
		Age  int
	}{
		{"Gopher", 7},
		{"Alice", 55},
		{"Vera", 24},
		{"Bob", 75},
	}
	sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
	fmt.Println("By name:", people)

	sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
	fmt.Println("By age:", people)
}
-----------------------------------------------------------------------
By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]

Sort custom data structures

  • generic sort.Sort, sort.Stable ν•¨μˆ˜λ₯Ό μ‚¬μš©ν•΄μ•Όν•œλ‹€. sort.Interface μΈν„°νŽ˜μ΄μŠ€λ₯Ό κ΅¬ν˜„ν–ˆλ‹€λ©΄ μ–΄λ–€ μ½œλ ‰μ…˜μ΄λ“  정렬이 κ°€λŠ₯ν•˜λ‹€.

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)
}
-------------------------------------------------------------------------
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}]
}

Last updated