Start learning free

LESSON 22 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort -r in Go: Descending Order with sort.Slice

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -r flag baked in. Given a list of lines, return them sorted in descending order by character code (the exact reverse of v1's order, like LC_ALL=C sort -r: lowercase letters come before uppercase ones), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

func sortLines(lines []string) string

Example:

Input: lines = ["banana", "apple", "cherry"]

Output: "cherry\nbanana\napple"

When printed:
cherry
banana
apple

Use sort.Slice with a less-function that returns sortedLines[i] > sortedLines[j] for descending order, then combine with strings.Join.

The full solution:
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")
}

STEP 1 OF 4
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Sort V2 in Go, explained

    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

    1. Write the signature sortLines(lines []string) string with its closing brace.
    2. Copy the input into sortedLines by appending it to a new, empty slice. sort.Slice works in place, so the copy protects the caller's data.
    3. Sort with sort.Slice, giving it the slice and a function of i and j that returns true when the element at i is bigger than the one at j. Bigger first means descending.
    4. 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 i and j are positions in the slice being sorted, so the function reads sortedLines[i] and sortedLines[j] itself. It is a closure: it uses the variable sortedLines from the enclosing function.
    • It must read the same slice that is being sorted. sort.Slice swaps elements as it goes, and the positions refer to the slice's current contents. Reading lines instead would compare the wrong elements.
    • The function literal fits on one line. func(i, j int) bool { return ... } is an anonymous function; i, j int means both parameters are int.
    • sort.Slice is 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 sort and strings.

    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 lines directly. 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 "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free