sort
最後更新
sort 提供排序與二分搜尋:可以排序內建型別的切片、用自訂比較函式排序任何切片,或排序實作了 sort.Interface 的自訂集合。這個套件做什麼
排序是把資料依某個規則排好順序;二分搜尋(binary search)是在排好的資料裡,每次砍掉一半範圍來快速找值。
sort 是 Go 早期就有的套件,在泛型出現前,它透過介面(sort.Interface)和 less(i, j) 函式支援任意型別。Go 1.21 加入泛型的 slices 後,大多數排序需求改用 slices 更簡潔也更快:| 需求 | sort 寫法 | slices 寫法(建議) |
|---|---|---|
排序 []int | sort.Ints(s) | slices.Sort(s) |
| 依欄位排序 | sort.Slice(s, func(i, j int) bool {...}) | slices.SortFunc(s, func(a, b T) int {...}) |
| 穩定排序 | sort.SliceStable | slices.SortStableFunc |
| 二分搜尋 | sort.SearchInts | slices.BinarySearch |
sort 仍然值得認識:大量既有程式碼使用它;sort.Interface 可以排序「不是切片」的資料結構(例如同時交換多個平行切片);sort.Search 可以對任何單調條件做二分搜尋,不限於切片。匯入
- import "sort"
常用 API
Ints、Strings 與 Float64s
把對應型別的切片原地遞增排序。
IntsAreSorted 等函式檢查是否已排序。簽名:
- func Ints(x []int)
- func Strings(x []string)
- func Float64s(x []float64)
- func IntsAreSorted(x []int) bool
範例:
- package main
- import (
- "fmt"
- "sort"
- )
- func main() {
- nums := []int{42, 7, 19, 3}
- fmt.Println(sort.IntsAreSorted(nums))
- sort.Ints(nums)
- fmt.Println(nums, sort.IntsAreSorted(nums))
- names := []string{"carol", "Alice", "bob"}
- sort.Strings(names)
- fmt.Println(names)
- vals := []float64{2.5, -1, 0.75}
- sort.Float64s(vals)
- fmt.Println(vals)
- }
輸出:
- false
- [3 7 19 42] true
- [Alice bob carol]
- [-1 0.75 2.5]
字串依位元組大小比較,大寫字母排在小寫之前,所以
Alice 在最前面。Slice 與 SliceStable
用
less(i, j) 函式排序任何切片:當索引 i 的元素應排在 j 前面時回傳 true。SliceStable 保留相等元素原本的先後順序(穩定排序),用於「先依 A 排、再依 B 排」的多次排序。注意:第一個參數必須是切片,否則會 panic。
less 收到的是索引而不是元素,要透過閉包存取切片本身。簽名:
- func Slice(x any, less func(i, j int) bool)
- func SliceStable(x any, less func(i, j int) bool)
範例:
- package main
- import (
- "fmt"
- "sort"
- )
- type Item struct {
- Name string
- Price int
- }
- func main() {
- items := []Item{{"pen", 30}, {"book", 250}, {"cup", 30}, {"bag", 250}}
- sort.SliceStable(items, func(i, j int) bool {
- return items[i].Price < items[j].Price
- })
- fmt.Println(items)
- sort.Slice(items, func(i, j int) bool {
- if items[i].Price != items[j].Price {
- return items[i].Price > items[j].Price
- }
- return items[i].Name < items[j].Name
- })
- fmt.Println(items)
- }
輸出:
- [{pen 30} {cup 30} {book 250} {bag 250}]
- [{bag 250} {book 250} {cup 30} {pen 30}]
sort.Interface 與 Sort
任何型別只要實作三個方法,就能交給
sort.Sort 排序:| 方法 | 意思 |
|---|---|
Len() int | 元素個數 |
Less(i, j int) bool | 第 i 個是否應排在第 j 個前面 |
Swap(i, j int) | 交換第 i 與第 j 個 |
這讓
sort 可以排序切片以外的結構,例如兩個平行切片(名字與分數分開存,但要一起交換)。介面的觀念見 介面基礎。sort.Stable 是穩定排序版本。簽名:
- type Interface interface {
- Len() int
- Less(i, j int) bool
- Swap(i, j int)
- }
- func Sort(data Interface)
- func Stable(data Interface)
範例:
- package main
- import (
- "fmt"
- "sort"
- )
- type Scoreboard struct {
- Names []string
- Scores []int
- }
- func (s Scoreboard) Len() int { return len(s.Names) }
- func (s Scoreboard) Less(i, j int) bool { return s.Scores[i] > s.Scores[j] }
- func (s Scoreboard) Swap(i, j int) {
- s.Names[i], s.Names[j] = s.Names[j], s.Names[i]
- s.Scores[i], s.Scores[j] = s.Scores[j], s.Scores[i]
- }
- func main() {
- board := Scoreboard{
- Names: []string{"ann", "bob", "cid"},
- Scores: []int{70, 95, 82},
- }
- sort.Sort(board)
- fmt.Println(board.Names, board.Scores)
- }
輸出:
- [bob cid ann] [95 82 70]
Reverse
包裝一個
sort.Interface,讓 Less 的結果反過來,達成遞減排序。sort.IntSlice、sort.StringSlice 是標準庫已經替 []int、[]string 實作好介面的型別,可以直接拿來用。簽名:
- func Reverse(data Interface) Interface
- type IntSlice []int
- type StringSlice []string
範例:
- package main
- import (
- "fmt"
- "sort"
- )
- func main() {
- nums := []int{3, 1, 4, 1, 5, 9}
- sort.Sort(sort.Reverse(sort.IntSlice(nums)))
- fmt.Println(nums)
- words := []string{"b", "c", "a"}
- sort.Sort(sort.Reverse(sort.StringSlice(words)))
- fmt.Println(words)
- }
輸出:
- [9 5 4 3 1 1]
- [c b a]
Search
在
[0, n) 範圍內用二分搜尋找出「第一個讓 f(i) 為 true 的索引」;都不成立時回傳 n。前提是 f 必須單調:某個位置之前全是 false,之後全是 true。它不只能找切片,任何「越往後越容易成立」的條件都能用,例如「最小的 i 使得 i*i >= 50」。
注意:回傳值等於
n 或該位置的元素不等於目標時,代表沒找到,要自己檢查。簽名:
- func Search(n int, f func(int) bool) int
範例:
- package main
- import (
- "fmt"
- "sort"
- )
- func main() {
- sorted := []int{2, 5, 8, 12, 16}
- target := 12
- i := sort.Search(len(sorted), func(i int) bool { return sorted[i] >= target })
- if i < len(sorted) && sorted[i] == target {
- fmt.Println("found at", i)
- }
- i = sort.Search(len(sorted), func(i int) bool { return sorted[i] >= 100 })
- fmt.Println(i == len(sorted))
- root := sort.Search(100, func(i int) bool { return i*i >= 50 })
- fmt.Println(root)
- }
輸出:
- found at 3
- true
- 8
SearchInts 與 SearchStrings
Search 的便利版本:在已遞增排序的 []int 或 []string 裡找目標值,回傳它的位置,或它應該被插入的位置。注意:回傳的是「插入位置」,不代表一定找到,要再比對該位置的值。
簽名:
- func SearchInts(a []int, x int) int
- func SearchStrings(a []string, x string) int
範例:
- package main
- import (
- "fmt"
- "sort"
- )
- func main() {
- a := []int{10, 20, 30, 40}
- for _, x := range []int{30, 25, 99} {
- i := sort.SearchInts(a, x)
- found := i < len(a) && a[i] == x
- fmt.Printf("x=%d index=%d found=%v\n", x, i, found)
- }
- fruits := []string{"apple", "banana", "cherry"}
- fmt.Println(sort.SearchStrings(fruits, "banana"))
- }
輸出:
- x=30 index=2 found=true
- x=25 index=2 found=false
- x=99 index=4 found=false
- 1
Find
Find(Go 1.19 起)用一個回傳 int 的比較函式做二分搜尋,同時回傳位置與是否找到,比 Search 少一步手動比對。比較函式的規則:目標小於第 i 個元素回傳負數、相等回傳 0、大於回傳正數。簽名:
- func Find(n int, cmp func(int) int) (i int, found bool)
範例:
- package main
- import (
- "fmt"
- "sort"
- "strings"
- )
- func main() {
- words := []string{"ant", "bee", "cat", "dog"}
- for _, target := range []string{"cat", "cow"} {
- i, found := sort.Find(len(words), func(i int) int {
- return strings.Compare(target, words[i])
- })
- fmt.Println(target, i, found)
- }
- }
輸出:
- cat 2 true
- cow 3 false
重點整理
- 新程式的排序優先用
slices;sort適合既有程式碼與非切片結構 sort.Slice的less收到索引,回傳true代表 i 排在 j 前面- 需要保留相等元素順序時用
SliceStable/Stable - 實作
Len、Less、Swap就能用sort.Sort;sort.Reverse反轉順序 Search回傳第一個讓條件成立的位置,找沒找到要自己比對;Find直接回傳是否找到