funcmain() { a := []string{"bag", "cat", "apple", "dog"} fmt.Println("before sort:", a) sort.Strings(a) //对字符串切片排序 // 也可以这样调用 sort.StringSlice(a).Sort() fmt.Println("after sort:", a)
b := []int{1, 3, 5, 2, 4, 6} fmt.Println("before sort:", b) sort.Ints(b) //对整数切片排序 // 也可以这样调用 sort.IntSlice(a).Sort() fmt.Println("after sort:", b)
c := []float64{2.0, 1.5, 3.3, 0.8} fmt.Println("before sort:", c) sort.Float64s(c) //对浮点数切片排序 // 也可以这样调用 sort.Float64Slice(a).Sort() fmt.Println("after sort:", c) }
// 输出 before sort: [bag cat apple dog] after sort: [apple bag cat dog] before sort: [135246] after sort: [123456] before sort: [21.53.30.8] after sort: [0.81.523.3]
type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with // index i should sort before the element with index j. Less(i, j int) bool // Swap swaps the elements with indexes i and j. Swap(i, j int) }
// Sort sorts data. // It makes one call to data.Len to determine n, and O(n*log(n)) calls to // data.Less and data.Swap. The sort is not guaranteed to be stable. funcSort(data Interface) { n := data.Len() quickSort(data, 0, n, maxDepth(n)) }
funcreconstructQueue(people [][]int) [][]int { re := make([][]int, 0) sort.Sort(heightAndRank(people)) for _, v := range people { insert(&re, v, v[1]) } return re }
funcinsert(re *[][]int, h []int, k int) { *re = append(*re, []int{}) copy((*re)[k+1:], (*re)[k:]) (*re)[k] = h } //自定义类型 type heightAndRank [][]int