Start learning free

LESSON 22 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V2 in Rust: Reverse Order with sort_by

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:

fn sort_lines(lines: Vec<String>) -> String

Example:

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

Output: "cherry\nbanana\napple"

When printed:
cherry
banana
apple

Sort with sort_by(|a, b| b.cmp(a)) to reverse the natural ordering, then combine the lines with join("\n").

The full solution:
impl Solution {
    fn sort_lines(lines: Vec<String>) -> String {
        let mut sorted_lines = lines;
        sorted_lines.sort_by(|a, b| b.cmp(a));
        sorted_lines.join("\n")
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Sort V2 in Rust, explained

    Problem overview

    Version 2 of the sort tool adds the -r flag: sort_lines returns the lines in descending order by character code, joined with \n. It is the exact reverse of version 1, so lowercase letters now come before uppercase ones. Duplicates are kept and an empty list gives the empty string. For ["banana", "apple", "cherry"] the result is "cherry\nbanana\napple". The previous version sorted ascending with a plain sort().

    Approach

    A plain sort() always goes ascending, so the lesson needs a custom comparison. sort_by takes a closure that receives two elements, a and b, and answers with an Ordering: Less if a belongs first, Equal, or Greater. Ascending order is a.cmp(b). Swapping the two operands, b.cmp(a), flips every answer, which gives descending order. Reversing the sorted vector afterwards would work too, but a swapped comparison does it in one step.

    Comparing by swapped operands is a general trick. Any ascending comparison turns into a descending one by exchanging a and b. For example, with the lines ["banana", "apple", "Cherry", ""], the ascending order is ["", "Cherry", "apple", "banana"], and the descending order is exactly that list reversed: ["banana", "apple", "Cherry", ""]. Because the two orders mirror each other, calling sort() followed by reverse() gives the same result for strings. The difference shows up with equal elements: a swapped comparison keeps equal elements in their input order, while reversing a sorted vector flips them. For identical strings you can't see that difference, since equal strings look the same wherever they land.

    The three possible answers of a comparison are the variants of the Ordering enum. For text, "b".cmp("a") is Greater and "Z".cmp("a") is Less, the same character-code rule as in the first version. In the closure, b.cmp(a) returns Less when b is smaller than a, and Less tells sort_by to place a before b. This is why the larger text ends up first.

    Step by step

    1. Bind the input as mutable to sorted_lines, because sorting changes the vector.
    2. Call sort_by with a closure over a and b that returns b.cmp(a). The closure decides where each pair goes.
    3. Return the join as the last expression, without return and without a semicolon. That expression is the function's value.

    The solution in Rust

    impl Solution {
        fn sort_lines(lines: Vec<String>) -> String {
            let mut sorted_lines = lines;
            sorted_lines.sort_by(|a, b| b.cmp(a));
            sorted_lines.join("\n")
        }
    }
    

    Rust details:

    • The closure's parameters are references. Here a and b are &String. The method cmp takes a reference to the other value, and b already is one, so b.cmp(a) needs no extra &.
    • Expression, not statement. A semicolon after sorted_lines.join("\n") would turn it into a statement and the function would return (), which fails to compile against the declared String.
    • Ordering. cmp comes from the Ord trait, which String implements with byte-by-byte comparison.

    Complexity

    Time: O(n log n) comparisons for n lines, each costing up to the length of the shorter line. Space: O(n) for the sort's buffer and the joined result.

    Edge cases and common mistakes

    • Writing a.cmp(b). That is ascending order, the previous version's result.
    • Case. ["apple", "Zebra", "", "apple"] gives "apple\napple\nZebra\n". The empty line sorts last, so the output ends with a newline character.
    • Empty list. The result is "".
    • Duplicates stay, side by side.

    Testing

    • ["banana", "apple", "cherry"] gives "cherry\nbanana\napple".
    • ["apple", "Zebra", "", "apple"] gives "apple\napple\nZebra\n".
    • [] gives "".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free