Start learning free

LESSON 395 OF 414 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: sort v3 — Numeric Sort in Rust

Practice

Build the next version of the Unix sort command, this time with the -n flag baked in. Each input line is the string form of an integer that fits in 32 bits (an optional leading -, no leading +; leading zeros such as "007" are allowed). Sort the lines numerically (not lexicographically) in ascending order, and return the original strings joined by newlines (\n). Lines with the same numeric value keep their original relative order (a stable sort). The real sort -n would break such ties by comparing the text; this version does not. If the list is empty, return the empty string.

Note: lexicographic sort would put "100" before "20"; numeric sort puts 20 before 100.

Function signature:

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

Example:

Input: lines = ["100", "20", "3", "10"]

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Sort by a key that parses each string into an i32 with parse, then build the result with the slice join method.

The full solution:
impl Solution {
    fn sort_lines(lines: Vec<String>) -> String {
        let mut sorted_lines = lines;
        sorted_lines.sort_by_key(|s| s.parse::<i32>().unwrap());
        return sorted_lines.join("\n");
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    Sort V3 in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free