一、包說明
這個包是一個golang內置的切片排序包,除了排序外還有一些其它的方法,可以對一些基本的可以比較大小的類型的切片進行排序,也可以通過實現排序接口的幾個特定方法實現自定義排序。
二、簡單的使用方法
1、可以使用sort.Ints()、sort.Strings()等內置方法對基本數據類型的切片進行排序
/*
* Author: oy
* Email: oyblog@qq.com
* Date: 2021/6/2 下午7:10
*/
package UnitTest
import (
"fmt"
"sort"
"testing"
)
func TestSort(t *testing.T) {
ints := []int{3, 2, 1}
strs := []string{"c", "d", "a"}
sort.Strings(strs)
sort.Ints(ints)
fmt.Printf("%v\n", ints)
fmt.Printf("%v\n", strs)
}
[1 2 3]
[a c d]
2、因為切片屬於引用類型,所以我們只需要將需要排序的切片傳給排序方法就可以了不需要寫成sort.Strings(&strs)
或 strs = sort.Strings(strs)
,這兩種寫法都會導致編譯失敗,使用方式很簡單這里不再做過多說明。
三、自定義排序
1、sort.Ints()
、sort.Strings()
等方法都是按升序排序的,如果我們希望按降序排序就需要我們自定義排序規則,自定義排序需要我們實現接口的Len()
、Less(i,j int)
、Swap(i,j int)
這三個方法。主要是實現Less(i,j int)
方法,這個方法里面寫排序算法(兩個元素比較大小的方式),Len()
方法是用來計算切片長度的直接return len(data)
就可以了,Swap(i,j int)
這個方法在調用排序方法后調換兩個元素的位置可以寫死成 ints[i], ints[j] = ints[j], ints[i]
,當Less()
返回True
時就會調用Swap()
方法,調換兩個相鄰元素的位置。
// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
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 // i>j 元素i在元素j的前面
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
2、對int切片按降序排序
/*
* email: oyblog@qq.com
* Author: oy
* Date: 2021/6/2 下午7:10
*/
package UnitTest
import (
"fmt"
"sort"
"testing"
)
type IntList []int
func (ints IntList) Len() int {
return len(ints)
}
func (ints IntList) Less(i, j int) bool { //返回True時會調用Swap方法調換兩個元素的位置
return ints[i] > ints[j] // (i>j),ints[i] < ints[j] 表示按升序排序,ints[i] > ints[j] 表示按降序排序
}
func (ints IntList) Swap(i, j int) {
ints[i], ints[j] = ints[j], ints[i]
}
func TestSort(t *testing.T) {
ints := IntList{}
ints = []int{1, 2, 3, 4, 56, 6}
sort.Sort(ints)
fmt.Printf("%v\n", ints)
}
=== RUN TestSort
[56 6 4 3 2 1]
--- PASS: TestSort (0.00s)
PASS
四、使用心得
1、sort.Strings()方法並不能對字符串數字排序,雖然不會報錯但是結果是錯的,貌似是以字符串的第一位排的
2、應用場景,固定排序。