sort 包 在內部實現了四種基本的排序算法:插入排序(insertionSort)、歸並排序(symMerge)、堆排序(heapSort)和快速排序(quickSort);sort包會依據實際數據自動選擇最優的排序算法。所以我們寫代碼時只需要考慮實現 sort.Interface 這個類型就可以了。
1. 對 []int 和 []string字符串進行排序
package main import ( "fmt" "sort" ) func main() { // []int排序 nums := []int{2, 31, 5, 6, 3} //順序 sort.Ints(nums) fmt.Println("1: ", nums) //使用 sort.Reverse 進行逆序排序 sort.Sort(sort.Reverse(sort.IntSlice(nums))) fmt.Println("2: ", nums) // []string字符串排序 names := []string{"abc", "12", "kk", "Jordan", "Ko", "DD"} // 順序 sort.Strings(names) fmt.Println("3: ", names) // 逆序 sort.Sort(sort.Reverse(sort.StringSlice(names))) fmt.Printf("4: After Reverse: %#v\n", names) //查找 // [0,100) // 二分查找 nums = []int{1, 3, 5, 7, 9} fmt.Println("5: ", nums[sort.SearchInts(nums, 8)] == 8) fmt.Println("6: ", nums[sort.SearchInts(nums, 5)] == 5) } /* $ go run sort.go 1: [2 3 5 6 31] 2: [31 6 5 3 2] 3: [12 DD Jordan Ko abc kk] 4: After Reverse: []string{"kk", "abc", "Ko", "Jordan", "DD", "12"} 5: false 6: true */
2. 使用 sort.Stable 進行穩定排序。
sort.Sort 並不保證排序的穩定性。如果有需要, 可以使用 sort.Stable。
package main import ( "fmt" "sort" ) type person struct { Name string Age int } type personSlice []person func (s personSlice) Len() int { return len(s) } func (s personSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func (s personSlice) Less(i, j int) bool { return s[i].Age < s[j].Age } func main() { a := personSlice{ { Name: "AAA", Age: 55, }, { Name: "BBB", Age: 22, }, { Name: "CCC", Age: 0, }, { Name: "DDD", Age: 22, }, { Name: "EEE", Age: 11, }, } sort.Stable(a) fmt.Println(a) }
結果:
$ go run sort-detail.go [{CCC 0} {EEE 11} {BBB 22} {DDD 22} {AAA 55}]