go内置数据类型(四)

  • 2023-08-15 11:31:31
  • 891
  • 0
  • go
  • authen

一、sort包

1、内置正排序:

package main

import (
	"fmt"
	"sort"
)

func main() {
	intSlice := []int{3, 1, 2, 5, 4}
	float64Slice := []float64{3.2, 1.0, 2.1, 5.4, 4.3}
	stringSlice := []string{"abcd", "aacd", "bcda", "d"}

	sort.Ints(intSlice)			//1, 2, 3, 4, 5
	sort.Float64s(float64Slice)	//1.0, 2.1, 3.2, 4.3, 5.4
	sort.Strings(stringSlice)	//"aacd", "abcd", "bcda", "d"
}

2、内置倒排序

package main

import (
	"fmt"
	"sort"
)

func main() {
	intSlice := []int{3, 1, 2, 5, 4}
	float64Slice := []float64{3.2, 1.0, 2.1, 5.4, 4.3}
	stringSlice := []string{"abcd", "aacd", "bcda", "d"}

	sort.Sort(sort.Reverse(sort.IntSlice(intSlice)))
	//5, 4, 3, 2, 1
	sort.Sort(sort.Reverse(sort.Float64Slice(float64Slice)))
	//5.4, 4.3, 3.2, 2.1, 1.0
	sort.Sort(sort.Reverse(sort.StringSlice(stringSlice)))
	//"d", "bcda", "abcd", "aacd"
}

 


发表评论

* *