Problem overview
This version of the sort tool has the -r flag built in. sortLines takes a slice of strings and returns them in descending order by character code, joined by "\n". It is the exact reverse of the ascending order, like LC_ALL=C sort -r: lowercase letters come before uppercase ones, and an empty line comes last. Duplicates are kept, and an empty slice gives the empty string.
The example ["banana", "apple", "cherry"] becomes "cherry\nbanana\napple".
Approach: describe the order yourself
sort.Strings only sorts upward. To control the direction, use sort.Slice, which sorts any slice according to a function you supply. That function, called a less function, receives two positions i and j and answers one question: should the element at i go before the element at j?
For ascending order the answer is "when it is smaller". For descending order the answer is "when it is bigger", so the function returns sortedLines[i] > sortedLines[j]. Go compares strings with < and > byte by byte, which is the character-code order the lesson asks for.
As before, the function sorts a copy so that the caller's slice stays in its original order, and then joins the lines with strings.Join.
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.sort.Sliceworks in place, so the copy protects the caller's data. - Sort with
sort.Slice, giving it the slice and a function ofiandjthat returns true when the element atiis bigger than the one atj. Bigger first means descending. - Join with
"\n"and return the result.
The solution in Go
func sortLines(lines []string) string {
sortedLines := append([]string{}, lines...)
sort.Slice(sortedLines, func(i, j int) bool { return sortedLines[i] > sortedLines[j] })
return strings.Join(sortedLines, "\n")
}
Go details to notice:
- The less function gets indices, not values. The parameters
iandjare positions in the slice being sorted, so the function readssortedLines[i]andsortedLines[j]itself. It is a closure: it uses the variablesortedLinesfrom the enclosing function. - It must read the same slice that is being sorted.
sort.Sliceswaps elements as it goes, and the positions refer to the slice's current contents. Readinglinesinstead would compare the wrong elements. - The function literal fits on one line.
func(i, j int) bool { return ... }is an anonymous function;i, j intmeans both parameters areint. sort.Sliceis not stable. Equal elements may end up in either order. For plain strings this makes no difference, because two equal strings are indistinguishable.- Imports. The code uses
sortandstrings.
Complexity
Time: O(n log n) comparisons for n lines, plus O(n) to copy and join. Each comparison costs up to the length of the strings compared.
Space: O(n) for the copy and the joined output. The sort is in place.
Edge cases and common mistakes
- Case order flips.
["apple", "Zebra"]gives"apple\nZebra": lowercase letters have larger codes, so they come first when sorting downward. - Empty lines go last.
["b", "", "a"]gives"b\na\n". The empty line is the smallest string, so it ends up at the bottom, and the output ends with a newline character that belongs to the empty last line. - Duplicates.
["b", "a", "b"]gives"b\nb\na". - Prefixes.
["ap", "apple", "app"]gives"apple\napp\nap": the longer string is bigger, so it comes first. - Using
<by mistake. That gives ascending order, the previous version's result. - Using
>=. A less function should be a strict "comes before", false for equal elements. Using>=breaks that rule, and the sort's behaviour is then not guaranteed. - Sorting
linesdirectly. This reorders the caller's slice.
Testing
["banana", "apple", "cherry"]gives"cherry\nbanana\napple".["apple", "Zebra"]gives"apple\nZebra".["b", "", "a"]gives"b\na\n".["b", "a", "b"]gives"b\nb\na".["ap", "apple", "app"]gives"apple\napp\nap".["x"]gives"x", and an empty slice gives"".
