Start learning free

LESSON 23 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V3 in C#: Stable Numeric Sort with OrderBy

Practice Read the full explanation

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:

public string SortLines(List<string> lines)

Example:

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

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Reorder with LINQ's OrderBy (a stable sort, unlike List.Sort), keyed on int.Parse of each string, then turn it back into a list. The strings themselves stay unchanged.

The full solution:
class Solution {
    public string SortLines(List<string> lines) {
        List<string> sortedLines = new List<string>(lines);
        sortedLines = sortedLines.OrderBy(s => int.Parse(s)).ToList();
        return string.Join("\n", sortedLines);
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in C#, explained

    Problem overview

    The method SortLines takes a List<string> in which every line is the text of a 32-bit integer: an optional leading -, no +, and possibly leading zeros such as "007". It sorts the lines by numeric value, ascending, and returns the original strings joined by "\n". Lines with the same value must keep their original relative order. An empty list gives "".

    For ["100", "20", "3", "10"] the result is "3\n10\n20\n100". Sorted as text, the same input would give "10\n100\n20\n3", because "1" comes before "2" and "3" character by character. Comparing numbers needs the numbers themselves.

    Approach: sort by a key, keep the text

    The output must contain the original strings, so "007" stays "007", not "7". That rules out converting every line to an int and printing the numbers. Instead, sort the strings by a key: the number each one stands for.

    LINQ's OrderBy does that. You give it a function that computes the key for each element, and it orders the elements by their keys. It also has a property this lesson needs: OrderBy is a stable sort, so elements with equal keys keep their original order. "7" and "007" both have the key 7, and they come out in the order they went in.

    Step by step

    1. Copy the input into sortedLines with new List<string>(lines).
    2. Replace sortedLines with a sorted version. OrderBy(s => int.Parse(s)) orders the strings by the number int.Parse reads from each one. OrderBy does not sort the list in place. It returns a sequence, so ToList() turns the result back into a List<string>.
    3. Return string.Join("\n", sortedLines).

    The solution in C#

    class Solution {
        public string SortLines(List<string> lines) {
            List<string> sortedLines = new List<string>(lines);
            sortedLines = sortedLines.OrderBy(s => int.Parse(s)).ToList();
            return string.Join("\n", sortedLines);
        }
    }
    

    The C# details:

    • OrderBy versus Sort. List<T>.Sort reorders the list itself and is not guaranteed to be stable. OrderBy leaves its source alone, returns a new ordered sequence and is stable. When equal elements must keep their order, use OrderBy.
    • OrderBy and ToList come from LINQ, which lives in System.Linq.
    • The sequence is lazy. OrderBy by itself sorts nothing yet. The work happens when the sequence is read, here by ToList().
    • int.Parse understands signs and leading zeros. int.Parse("-5") is -5 and int.Parse("007") is 7. Text that isn't a number, such as "x", throws a FormatException. The lesson promises valid integers, so no check is needed.
    • The key is computed once per element, not once per comparison, so each line is parsed once.

    Complexity

    Time: O(n log n). Parsing is linear in the total text length, and sorting n keys takes O(n log n) comparisons of ints, each in constant time. Space: O(n) for the copy, the keys, the sorted list and the joined string.

    Edge cases and common mistakes

    • Empty list. The sorted list is empty and the result is "".
    • Ties keep their order. ["10", "010", "1", "-5", "007", "7"] gives "-5\n1\n007\n7\n10\n010". "007" stays before "7" and "10" before "010", as in the input.
    • Negative numbers. A text sort puts "-5" in odd places. The numeric key puts it first.
    • The extremes. ["2147483647", "-2147483648", "0"] gives "-2147483648\n0\n2147483647", because both values fit in an int.
    • Keeping the numbers instead of the text. Parsing into a list of ints and joining those would print 7 where the input had 007.
    • Using Sort with a comparison. It can work, but equal values may come out in a different order than they went in.

    Testing

    • ["100", "20", "3", "10"] gives "3\n10\n20\n100".
    • ["10", "010", "1", "-5", "007", "7"] gives "-5\n1\n007\n7\n10\n010".
    • [] gives "".
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free