Simple Usage of Sort in Golang

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值