How do I sort strings like 4.3.4, 4.3.30 in golang. There is a method named "sort" in golang? The issue is that with this method 4.3.30 prints before 4.3.4. I want 4.3.30 to print after 4.3.4. What is the logic to do this sorting? Note- I just need a logic weather it will be in go or java. Thanks in advance. for you reference, "sort" program in go:
package main
import "sort"
import "fmt"
type ByLength []string
func (s ByLength) Len() int {
return len(s)
}
func (s ByLength) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s ByLength) Less(i, j int) bool {
return (s[i]) < (s[j])
}
func main() {
abc := []string{"1.5.8", "5.8.4", "4.3.30"}
sort.Sort(ByLength(abc))
fmt.Println(abc)
}
Strings without special handling are sorted lexicographically.
This means that "30" in string terms is smaller than "4" because the character "3" is lexicographically smaller than the character "4".
If you want to sort these based on integer values within the string, you need to make your own sorter.
So in your comparator function func (s ByLength) Less(i, j int) bool
, you can do something along the lines of:
.
This of course only works for the .
separated strings, you would have to adapt this for other separators. You also have to worry about non-integer parts and strings with different number of parts (eg: 4.3
vs 4.3.5
)