43. Go - Sorts and Custom Sorts

Go built in sort functions can sort default slice variables and also custom ones.


Example: Ints and Strings

package main

import (
    "fmt"
    "sort"
)

func main() {
    numbers := []int{5, 2, 8, 2, 52, 111}
    words := []string{"hello", "die", "pink", "ablw"}

    fmt.Println(numbers)
    fmt.Println(words)

    sort.Ints(numbers)
    sort.Strings(words)

    fmt.Println(numbers)
    fmt.Println(words)

}


Custom Sort: requires giving the type of data we want to sort a list of similar methods of the built in sort functions so they can be of the same interface. https://pkg.go.dev/sort#example-package

Using sort.Sort(Custom(struct))

Example:

package main

import (
    "fmt"
    "sort"
)

type blob struct {
    Size int
    Name string
}

type bySize []blob
type byName []blob

func (a bySize) Len() int           { return len(a) }
func (a bySize) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a bySize) Less(i, j int) bool { return a[i].Size < a[j].Size }

func (a byName) Len() int           { return len(a) }
func (a byName) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a byName) Less(i, j int) bool { return a[i].Name < a[j].Name }

func main() {
    blob1 := blob{5, "red"}
    blob2 := blob{6, "blue"}
    blob3 := blob{7, "orange"}
    blob4 := blob{8, "white"}
    blob5 := blob{9, "pink"}

    blobs := []blob{blob1, blob2, blob3, blob4, blob5}
    fmt.Println(blobs)
    sort.Sort(bySize(blobs))
    fmt.Println(blobs)
    sort.Sort(byName(blobs))
    fmt.Println(blobs)
}


Comments

Popular posts from this blog

2. FreeCodeCamp - Dynamic Programming - Learn to Solve Algorithmic Problems & Coding Challenges

20. Data Analytics - Analyze Data to Answer Questions - Week 1

3. Algorithms - Selection Sort