Simple Usage of Sort in Golang
Golang provide the package “sort” to reorder the []int
, []float64
and []string
. The sort algorithm it uses include Insert Sort, Quick Sort and Heap Sort. As other languages, these three algorithms are not open.
Type Interface
Any data structure (usually be set) which implements the sort.interface
could use the methods in this package to reorder, this is based on the index of data is Integer.
type Interface interface {
Len() int //the total number of the set
Less(i, j int) //if set[i] < set[j]
Swap(i, j int) //swap the value of the data which index is i and j
}
For []int
The Golang has a built-in method sort.Ints
for reordering the Integer Array by an ascending order. It’s usage as follow:
package main
import (
"fmt"
"sort"
)
type IntSlice []int
func main() {
slice := IntSlice{2, 6, 4, 5, 8, 2, 0}
sort.Ints(slice)
fmt.Println(slice)
}
And the outcome is:
[0 2 2 4 5 6 8]
If we want to reorder the array by a descending order, we have to implement the three functions in sort.interface
package main
import (
"fmt"
"sort"
)
type Integer []int
func (a Integer) Len() int { return len(a) }
func (a Integer) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a Integer) Less(i, j int) bool { return a[i] > a[j] }
func main() {
slice := Integer{2, 6, 4, 5, 8, 2, 0}
sort.Ints(slice)
fmt.Println("sort.Ints: ", slice)
sort.Stable(slice)
fmt.Println("sort.Stable:", slice)
sort.Sort(slice)
fmt.Println("sort.Sort: ", slice)
}
The outcome:
sort.Ints: [0 2 2 4 5 6 8]
sort.Stable: [8 6 5 4 2 2 0]
sort.Sort: [8 6 5 4 2 2 0]
The sort.Sort()
is not a stable sort algorithm, it will change the sequence when values of two data elements are equal. However, Golang also provides a stable method sort.Stable()
The method sort.isSorted
is used to determine that if the array is ordered, the value it returns is bool
. For example :
func main() {
slice := Integer{2, 4, 5, 1, 6, 7}
fmt.Println(sort.isSorted(slice))
}
Then it will display:
false
The sort.Search(len int, func(i int) bool)
is usually used in condition that the array or slice is sorted by an ascending order to look for the index of element that match this func. For example:
func main() {
slice := Integer{2, 6, 4, 5, 8, 2, 0}
sort.Ints(slice)
index := sort.Search(len(slice), func(i int) bool { return slice[i] == 4 })
fmt.Printf("slice[%d] = %d\n", index, slice[index])
}
Then:
slice[3] = 4
For Custom Data Structure
The same as the Integer. Talk is cheap, show the code directly:
package main
import (
"fmt"
"sort"
)
type Character struct {
name string
attackPower int
}
type favor []Character
func (a favor) Len() int { return len(a) }
func (a favor) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a favor) Less(i, j int) bool { return a[i].attackPower < a[j].attackPower }
func main() {
love := favor{
{name: "Arutoria Pendoragon", attackPower: 5300},
{name: "Kurumi", attackPower: 6400},
{name: "Emilia", attackPower: 2500},
}
fmt.Println("Before Sort...")
display(love)
fmt.Println("After Sort...")
sort.Stable(love)
display(love)
}
func display(love favor) {
for _, value := range love {
fmt.Printf("name=%s, attack=%d\n", value.name, value.attackPower)
}
}
Then, these will display:
Before Sort...
name=Arutoria Pendoragon, attack=5300
name=Kurumi, attack=6400
name=Emilia, attack=2500
After Sort...
name=Emilia, attack=2500
name=Arutoria Pendoragon, attack=5300
name=Kurumi, attack=6400