基本类型
1,sort包提供了三个切片类型sort.StringSlice,sort.IntSlice,sort.Float64Slice。可以对这三种类型进行便捷排序。
2,需要对序列满足以上三个切片类型之一,可直接调用sort.Sort()方法进行排序,无需定义三要素。
3,其实实现原理就是把满足这三种切片类型的三要素函数直接定义在了底层,用户无需定义,直接调用sort.Sort()方法即可拿到排序结果,默认升序。如果需要逆序,调用sort.Reverse()函数即可。
demoString := sort.StringSlice{
...
}
//正序
sort.Sort(demoString)
//逆序
sort.Sort( sort.Reverse(demoString) )
func speedySort(){
//直接定义字符串序列为StringSlice
stringTmp := sort.StringSlice{
"3-golang",
"4-c",
"5-cpp",
"1-php",
"2-java",
"6-python",
}
sort.Sort(stringTmp)
fmt.Println(stringTmp)
//[1-php 2-java 3-golang 4-c 5-cpp 6-python]
sort.Sort( sort.Reverse(stringTmp) )
fmt.Println(stringTmp)
//[6-python 5-cpp 4-c 3-golang 2-java 1-php]
intTmp := []int{
6,3,9,8,1,2,5,7,
}
//转换intTmp为IntSlice类型
sort.Sort( sort.IntSlice(intTmp) )
fmt.Println(intTmp)
//[1 2 3 5 6 7 8 9]
sort.Sort( sort.Reverse( sort.IntSlice(intTmp) ) )
fmt.Println(intTmp)
//[9 8 7 6 5 3 2 1]
}
Go 1.8之后的版本,Go语言在 sort 包中提供了 sort.Slice() 函数进行更为简便的排序方法。
sort.Slice() 函数只要求传入需要排序的数据,以及一个排序时对元素的回调函数
sort.Slice(tmp,func(i,j int){
return tmp[i]<tmp[j]
})
func demoSortSlice(){
a := []int{6,3,9,8,1,2,5,7}
sort.Slice(a, func(i, j int) bool {
return a[i]>a[j]
})
fmt.Println(a)
//[9 8 7 6 5 3 2 1]
}
对于将要排序的数组类型只需要我们实现下面三种方法:
type Interface interface {
Len() int // 数组长度
Less(i, j int) bool //两个元素的大小比较
Swap(i, j int) // 交换两个元素
}
举个栗子
有一个Student数组,现要对其按照年龄大小,从小到大进行排序
type Student struct {
Name string
Age int
}
students:=[]Student{
{Name: "tom",Age: 10},
{Name: "smith",Age: 12},
{Name: "danny",Age: 13},
{Name: "jack",Age: 12},
{Name: "boom",Age: 12},
}
第一步,构造数组对象
type StudentArray []Student
第二步,实现 Len(),Less(),Swap() 三种方法
func (array StudentArray) Len() int {
return len(array)
}
func (array StudentArray) Less(i,j int) bool {
return array[i].Age < array[j].Age //从小到大, 若为大于号,则从大到小
}
func (array StudentArray) Swap(i,j int) {
array[i],array[j] = array[j],array[i]
}
第三步,调用sort包
sort.Sort(StudentArray(students))
第四步,输出排序后的结果
fmt.Println(students)
// [{tom 10} {smith 12} {jack 12} {boom 12} {danny 13}]
现在呢,又提出了一个新的排序需求:
从小到大按年龄排序
当年龄相同时,按照名字排序
问题不大,我们只需要更新Less()方法即可:
func (array StudentArray) Less(i,j int) bool {
if array[i].Age == array[j].Age {
return array[i].Name < array[j].Name
}
return array[i].Age < array[j].Age
}
此时再进行排序
sort.Sort(StudentArray(students))
fmt.Println(students)
//[{tom 10} {boom 12} {jack 12} {smith 12} {danny 13}]