-1

I'm trying to sort slice of int inside a slice, for example :

slices := make([][]int32, 0)
slices = append(slices, []int32{10,22})
slices = append(slices, []int32{13,22})
slices = append(slices, []int32{12,22})
// [[10 22] [13 22] [12 22]]
// to become 
// [[10 22] [12 22] [13 22]] (ascending)
// *by the first element in slice

i had no idea for that, but i was thinking about append and prepend after check

4

1 回答 1

1

您只需要使用 sort 包中的 Slice

package main

import (
    "fmt"
    "sort"
)
func main() {
    a := [][]int{[]int{10,3}, []int{5,12}, []int{5, 3}, []int{1,1}}
    fmt.Printf("before: %v\n", a)
    sort.Slice(a, func(i,j int) bool{ return a[i][0] < a[j][0]})
    fmt.Printf("after: %v\n", a)
}

对于稳定的排序使用, sort.SliceStable 代替。

于 2019-02-19T02:50:13.007 回答