字符串数字的排序,在日常工作中比较常见。
举例:
s := [...]string{"20", "5", "10", "50", "15", "25", "55", "35", "40", "0", "45", "30"}
方法一:
func Sort1() []string{
s := []string{"20","5","10","50","15","25","55","35","40","0","45","30"}
sort.Slice(s, func(i, j int) bool {
numA, _ := strconv.Atoi(s[i])
numB, _ := strconv.Atoi(s[j])
return numA < numB
})
return s
}
方法二:
func Sort2() []string{
s := []string{"20","5","10","50","15","25","55","35","40","0","45","30"}
f := func(ss string) uint64 {
b64 := make([]byte, 64/8)
if len(ss) > 0 {
u64, err := strconv.ParseUint(ss, 10, 64)
if err == nil {
binary.BigEndian.PutUint64(b64, u64+1)
}
return u64
}
return 0
}
sort.Slice(s, func(i, j int) bool {
return f(s[i]) < f(s[j])
})
return s
}
前两种方法来源网上, 方法三:
func sortStringNumber(s []string) []string {
sort.Slice(s, func(i, j int) bool {
var numA, numB string
if len(s[i]) == 1 {
numA = "0" + s[i]
if len(s[j]) == 1 {
numB = "0" + s[j]
} else {
numB = s[j]
}
} else if len(s[j]) == 1 {
numA = s[i]
numB = "0" + s[j]
} else {
numA = s[i]
numB = s[j]
}
if numA[0] > numB[0] {
return false
} else if numA[0] == numB[0] && numA[1] > numB[1] {
return false
}
return true
})
return s
}
三种benchmark比较:
BenchmarkSort1
BenchmarkSort1-4 1635199 742 ns/op
BenchmarkSort2
BenchmarkSort2-4 987405 1160 ns/op
BenchmarkSort3
BenchmarkSort3-4 2033178 591 ns/op
总结:方法三性能略有提升,后续还需优化