Skip to content

排序

go
package main

import (
    "fmt"
    "sort"
)

func main() {

    strs := []string{"c", "a", "b"}
    sort.Strings(strs)
    fmt.Println("Strings:", strs)

    ints := []int{7, 2, 4}
    sort.Ints(ints)
    fmt.Println("Ints:   ", ints)

    s := sort.IntsAreSorted(ints)
    fmt.Println("Sorted: ", s)
}

注意,例子中的是 slice 而不是 array。

IntsAreSorted 的本质

go
for i := 1; i < len(data); i++ {
    if data[i] < data[i-1] {
        return false
    }
}
return true

拷贝 slice

copySlice := append([]int(nil), ints...)
sort.Ints(copySlice)
copySlice := make([]int, len(ints))
copy(copySlice, ints)