Problem overview
This version of sort has the -n flag built in. Every line is the text of an integer that fits in 32 bits: an optional leading -, no leading +, and leading zeros such as "007" are allowed. sortLines sorts the lines by numeric value, ascending, and returns the original strings joined by "\n".
Lines with the same value keep their input order, which is a stable sort. (The real sort -n breaks ties by comparing the text, but this version does not.) An empty slice gives the empty string.
For ["100", "20", "3", "10"] the result is "3\n10\n20\n100". Sorting as text would put "100" first, since 1 is smaller than 2 and 3 as a character. Sorting as numbers puts 3 first.
Approach: compare numbers, return the strings
The output must contain the original strings, so "007" stays "007". The numbers are needed only to decide the order. The plan is to sort a copy of the lines with a less function that converts the two lines it is asked about to int and compares them.
Two ties need thought. "7", "007" and "07" are all the number 7, and they must come out in the order they came in. sort.Slice does not promise that, but sort.SliceStable does: it takes the same arguments and keeps equal elements in their original relative order. Equal here means the less function says neither one goes before the other, which is exactly the case for equal numbers.
Step by step
- Write the signature
sortLines(lines []string) stringwith its closing brace. - Copy the input into
sortedLinesby appending it to a new, empty slice, so the caller's slice is untouched. - Call
sort.SliceStableon the copy with a function of two positionsiandjthat returns abool. Write the closing})immediately and fill in the body. - Parse the line at
iwithstrconv.Atoiintoai.Atoireturns the number and an error; the blank identifier_discards the error. - Parse the line at
jintoajthe same way. - Return
ai < aj. True means the line atigoes first, which gives ascending order. - Join the sorted copy with
"\n"and return it.
The solution in Go
func sortLines(lines []string) string {
sortedLines := append([]string{}, lines...)
sort.SliceStable(sortedLines, func(i, j int) bool {
ai, _ := strconv.Atoi(sortedLines[i])
aj, _ := strconv.Atoi(sortedLines[j])
return ai < aj
})
return strings.Join(sortedLines, "\n")
}
Go details to notice:
strconv.Atoireturns two values. Go has no exceptions: a function that can fail returns an error as a second value.ai, _ := ...keeps the number and throws the error away. That is safe here because every line is guaranteed to be a valid integer. For input like"12a",Atoireturns 0 together with an error sayingparsing "12a": invalid syntax, so ignoring errors on untrusted input would silently turn bad lines into zeros.- Leading zeros and signs are fine.
Atoi("007")is 7 andAtoi("-12")is -12. The number is used only for comparing: the output keeps the original text. intis 64 bits here, so any 32-bit value converts and compares without overflow.- The less function reads the slice being sorted. The positions
iandjrefer tosortedLinesas it is rearranged during the sort, so the function must readsortedLines, notlines. - Stability matters only for ties. The comparison
ai < ajis false in both directions for equal numbers, andSliceStablethen leaves those elements in input order.
Complexity
Time: O(n log n) comparisons for n lines, and each comparison parses two short strings. The solution parses again on every comparison instead of once per line. For a lesson-sized input that is fine, and it keeps the code short. Parsing each line once into a separate slice of numbers would avoid the repeated work.
Space: O(n) for the copy and the joined output.
Edge cases and common mistakes
- Sorting as text.
sort.Stringson["100", "20", "3", "10"]gives[10 100 20 3]. Numeric order needs the conversion. - Negative numbers.
["-5", "3", "-20", "0"]gives"-20\n-5\n0\n3". As text,-would mislead the order, but as numbers it works. - Equal values with different text.
["007", "7", "07", "6"]gives"6\n007\n7\n07", and["7", "007", "07"]comes back unchanged. The tied lines keep their input order. - Using
sort.Slice. It may reorder tied lines, so a test with equal numbers can fail unpredictably. UseSliceStable. - Returning numbers instead of the original text. The result must contain
"007", not"7". - Empty input. An empty slice gives
"".
Testing
["100", "20", "3", "10"]gives"3\n10\n20\n100".["-5", "3", "-20", "0"]gives"-20\n-5\n0\n3".["007", "7", "07", "6"]gives"6\n007\n7\n07".["7", "007", "07"]gives"7\n007\n07".- An empty slice gives
"".
