GO成神之路: 排序的实现与原理(一)|Go主题月

1,163 阅读2分钟

在数据结构存在大量的篇幅在介绍各种排序算法,可见排序在日常开发的重要性。

对各种排序算法感兴趣的朋友可以浏览Python实现多种排序算法查找你想了解的排序算法实现。

这里我们不讲如何用Go实现各种排序算法,我们讨论Go中的排序是如何设计的。

Go中已经实现的排序类型有哪些

  • sort.Ints

    对int切片进行排序

  • sort.Float64s

    对Float64切片进行排序

  • sort.Strings

    对String切片进行排序

正序排列

sort.Ints调用sort.Sort进行排序,内部使用的是快速排序算法

sortInts := []int{2, 3, 4, 1}
sort.Ints(sortInts)
log.Println(sortInts)

# out
[1,2,3,4]

反序

sortInts := []int{2, 3, 4, 1}
sort.Sort(sort.Reverse(sort.IntSlice(sortInts)))
log.Println(sortInts)

# out
[4 3 2 1]

判断一个集合是不是有序的

isSort:=sort.IsSorted(sort.IntSlice([]int{1,2,3,4}))
log.Println(isSort)
// 简写
isSort=sort.IntsAreSorted([]int{1,2,3,4})
log.Println(isSort)

# out
true
true

稳定排序

与sort.Sort不同的是:sort.Stable会根据元素个数的不同,自动选择更合适的排序方式,内部使用了直接插入排序与归并排序

sortInts := []int{2, 4, 3, 1}
sort.Stable(sort.IntSlice(sortInts))
log.Println(sortInts)

有序集合的搜索

有序集合必须是按升序排排列的

非有序集合的搜索结果无法返回正确的索引,所以应避免搜索非有序集合。

sortInts := []int{1, 2, 3, 4}
index:=sort.Se(sortInts,2)
log.Println(index)

# out
1

自定义排序

模拟降序

sortInts := []int{1,5,8,10,4}
sort.Slice(sortInts, func(i, j int) bool {
        return sortInts[i]>sortInts[j]
})
log.Println(sortInts)

该函数支持对复杂类型进行排序

people := []struct {
    Name string
    Age  int
}{
    {"Gopher", 7},
    {"Alice", 55},
    {"Vera", 24},
    {"Bob", 75},
}
sort.Slice(people, func(i, j int) bool { return people[i].Name < people[j].Name })
fmt.Println("By name:", people)
sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
fmt.Println("By age:", people)

# out
By name: [{Alice 55} {Bob 75} {Gopher 7} {Vera 24}]
By age: [{Gopher 7} {Vera 24} {Alice 55} {Bob 75}]