sort

最後更新


sort 提供排序與二分搜尋:可以排序內建型別的切片、用自訂比較函式排序任何切片,或排序實作了 sort.Interface 的自訂集合。

這個套件做什麼


排序是把資料依某個規則排好順序;二分搜尋(binary search)是在排好的資料裡,每次砍掉一半範圍來快速找值。
sort 是 Go 早期就有的套件,在泛型出現前,它透過介面(sort.Interface)和 less(i, j) 函式支援任意型別。Go 1.21 加入泛型的 slices 後,大多數排序需求改用 slices 更簡潔也更快:
需求sort 寫法slices 寫法(建議)
排序 []intsort.Ints(s)slices.Sort(s)
依欄位排序sort.Slice(s, func(i, j int) bool {...})slices.SortFunc(s, func(a, b T) int {...})
穩定排序sort.SliceStableslices.SortStableFunc
二分搜尋sort.SearchIntsslices.BinarySearch

sort 仍然值得認識:大量既有程式碼使用它;sort.Interface 可以排序「不是切片」的資料結構(例如同時交換多個平行切片);sort.Search 可以對任何單調條件做二分搜尋,不限於切片。

匯入


  1. import "sort"

常用 API


Ints、Strings 與 Float64s


把對應型別的切片原地遞增排序。IntsAreSorted 等函式檢查是否已排序。
簽名:
  1. func Ints(x []int)
  2. func Strings(x []string)
  3. func Float64s(x []float64)
  4. func IntsAreSorted(x []int) bool

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func main() {
  7. nums := []int{42, 7, 19, 3}
  8. fmt.Println(sort.IntsAreSorted(nums))
  9. sort.Ints(nums)
  10. fmt.Println(nums, sort.IntsAreSorted(nums))
  11. names := []string{"carol", "Alice", "bob"}
  12. sort.Strings(names)
  13. fmt.Println(names)
  14. vals := []float64{2.5, -1, 0.75}
  15. sort.Float64s(vals)
  16. fmt.Println(vals)
  17. }

輸出:
  1. false
  2. [3 7 19 42] true
  3. [Alice bob carol]
  4. [-1 0.75 2.5]

字串依位元組大小比較,大寫字母排在小寫之前,所以 Alice 在最前面。

Slice 與 SliceStable


用 less(i, j) 函式排序任何切片:當索引 i 的元素應排在 j 前面時回傳 true。SliceStable 保留相等元素原本的先後順序(穩定排序),用於「先依 A 排、再依 B 排」的多次排序。
注意:第一個參數必須是切片,否則會 panic。less 收到的是索引而不是元素,要透過閉包存取切片本身。
簽名:
  1. func Slice(x any, less func(i, j int) bool)
  2. func SliceStable(x any, less func(i, j int) bool)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. type Item struct {
  7. Name string
  8. Price int
  9. }
  10. func main() {
  11. items := []Item{{"pen", 30}, {"book", 250}, {"cup", 30}, {"bag", 250}}
  12. sort.SliceStable(items, func(i, j int) bool {
  13. return items[i].Price < items[j].Price
  14. })
  15. fmt.Println(items)
  16. sort.Slice(items, func(i, j int) bool {
  17. if items[i].Price != items[j].Price {
  18. return items[i].Price > items[j].Price
  19. }
  20. return items[i].Name < items[j].Name
  21. })
  22. fmt.Println(items)
  23. }

輸出:
  1. [{pen 30} {cup 30} {book 250} {bag 250}]
  2. [{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 是穩定排序版本。
簽名:
  1. type Interface interface {
  2. Len() int
  3. Less(i, j int) bool
  4. Swap(i, j int)
  5. }
  6. func Sort(data Interface)
  7. func Stable(data Interface)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. type Scoreboard struct {
  7. Names []string
  8. Scores []int
  9. }
  10. func (s Scoreboard) Len() int { return len(s.Names) }
  11. func (s Scoreboard) Less(i, j int) bool { return s.Scores[i] > s.Scores[j] }
  12. func (s Scoreboard) Swap(i, j int) {
  13. s.Names[i], s.Names[j] = s.Names[j], s.Names[i]
  14. s.Scores[i], s.Scores[j] = s.Scores[j], s.Scores[i]
  15. }
  16. func main() {
  17. board := Scoreboard{
  18. Names: []string{"ann", "bob", "cid"},
  19. Scores: []int{70, 95, 82},
  20. }
  21. sort.Sort(board)
  22. fmt.Println(board.Names, board.Scores)
  23. }

輸出:
  1. [bob cid ann] [95 82 70]

Reverse


包裝一個 sort.Interface,讓 Less 的結果反過來,達成遞減排序。sort.IntSlice、sort.StringSlice 是標準庫已經替 []int、[]string 實作好介面的型別,可以直接拿來用。
簽名:
  1. func Reverse(data Interface) Interface
  2. type IntSlice []int
  3. type StringSlice []string

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func main() {
  7. nums := []int{3, 1, 4, 1, 5, 9}
  8. sort.Sort(sort.Reverse(sort.IntSlice(nums)))
  9. fmt.Println(nums)
  10. words := []string{"b", "c", "a"}
  11. sort.Sort(sort.Reverse(sort.StringSlice(words)))
  12. fmt.Println(words)
  13. }

輸出:
  1. [9 5 4 3 1 1]
  2. [c b a]


在 [0, n) 範圍內用二分搜尋找出「第一個讓 f(i) 為 true 的索引」;都不成立時回傳 n。前提是 f 必須單調:某個位置之前全是 false,之後全是 true。
它不只能找切片,任何「越往後越容易成立」的條件都能用,例如「最小的 i 使得 i*i >= 50」。
注意:回傳值等於 n 或該位置的元素不等於目標時,代表沒找到,要自己檢查。
簽名:
  1. func Search(n int, f func(int) bool) int

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func main() {
  7. sorted := []int{2, 5, 8, 12, 16}
  8. target := 12
  9. i := sort.Search(len(sorted), func(i int) bool { return sorted[i] >= target })
  10. if i < len(sorted) && sorted[i] == target {
  11. fmt.Println("found at", i)
  12. }
  13. i = sort.Search(len(sorted), func(i int) bool { return sorted[i] >= 100 })
  14. fmt.Println(i == len(sorted))
  15. root := sort.Search(100, func(i int) bool { return i*i >= 50 })
  16. fmt.Println(root)
  17. }

輸出:
  1. found at 3
  2. true
  3. 8

SearchInts 與 SearchStrings


Search 的便利版本:在已遞增排序的 []int 或 []string 裡找目標值,回傳它的位置,或它應該被插入的位置。
注意:回傳的是「插入位置」,不代表一定找到,要再比對該位置的值。
簽名:
  1. func SearchInts(a []int, x int) int
  2. func SearchStrings(a []string, x string) int

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. )
  6. func main() {
  7. a := []int{10, 20, 30, 40}
  8. for _, x := range []int{30, 25, 99} {
  9. i := sort.SearchInts(a, x)
  10. found := i < len(a) && a[i] == x
  11. fmt.Printf("x=%d index=%d found=%v\n", x, i, found)
  12. }
  13. fruits := []string{"apple", "banana", "cherry"}
  14. fmt.Println(sort.SearchStrings(fruits, "banana"))
  15. }

輸出:
  1. x=30 index=2 found=true
  2. x=25 index=2 found=false
  3. x=99 index=4 found=false
  4. 1

Find


Find(Go 1.19 起)用一個回傳 int 的比較函式做二分搜尋,同時回傳位置與是否找到,比 Search 少一步手動比對。比較函式的規則:目標小於第 i 個元素回傳負數、相等回傳 0、大於回傳正數。
簽名:
  1. func Find(n int, cmp func(int) int) (i int, found bool)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "sort"
  5. "strings"
  6. )
  7. func main() {
  8. words := []string{"ant", "bee", "cat", "dog"}
  9. for _, target := range []string{"cat", "cow"} {
  10. i, found := sort.Find(len(words), func(i int) int {
  11. return strings.Compare(target, words[i])
  12. })
  13. fmt.Println(target, i, found)
  14. }
  15. }

輸出:
  1. cat 2 true
  2. cow 3 false

重點整理


  • 新程式的排序優先用 slices;sort 適合既有程式碼與非切片結構
  • sort.Slice 的 less 收到索引,回傳 true 代表 i 排在 j 前面
  • 需要保留相等元素順序時用 SliceStable/Stable
  • 實作 Len、Less、Swap 就能用 sort.Sort;sort.Reverse 反轉順序
  • Search 回傳第一個讓條件成立的位置,找沒找到要自己比對;Find 直接回傳是否找到

資料來源