Start learning free

LESSON 21 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort V1 in C#: Ordinal Ascending Sort of Lines

Practice Read the full explanation

Build a tiny version of the Unix sort command. Given a list of lines, return them sorted in ascending order by character code (like LC_ALL=C sort: uppercase letters come before lowercase ones, "Zebra" before "apple", and an empty line comes first), joined by newline characters (\n). Duplicates are all kept. If the list is empty, return the empty string.

Function signature:

public string SortLines(string[] lines)

Example:

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

Output: "apple\nbanana\ncherry"

When printed:
apple
banana
cherry

Copy the input into a new List<string>, sort it in place with Sort(StringComparer.Ordinal), then stitch it together with string.Join.

The full solution:
class Solution {
    public string SortLines(string[] lines) {
        List<string> sortedLines = new List<string>(lines);
        sortedLines.Sort(StringComparer.Ordinal);
        return string.Join("\n", sortedLines);
    }
}

STEP 1 OF 3
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Sort V1 in C#, explained

    Problem overview

    The method SortLines receives a string[] of lines and returns them in ascending order, joined by "\n". The order is by character code, as in LC_ALL=C sort: every uppercase letter comes before every lowercase one, so "Zebra" comes before "apple", and an empty line comes first. Duplicates are kept, and an empty array gives "".

    For ["banana", "apple", "cherry"] the result is "apple\nbanana\ncherry".

    Approach: copy, sort with an ordinal comparer, join

    Sorting is already in the library, so the work is in picking the right tools. There are three decisions:

    1. A string[] has a fixed length and is the caller's own object. Sorting it in place would reorder the caller's data. The method sorts a copy instead.
    2. The comparison has to be by character code, not by the culture-aware default. StringComparer.Ordinal does exactly that.
    3. The sorted lines are glued together with string.Join.

    Step by step

    1. Build sortedLines as new List<string>(lines). The list constructor accepts any collection, here the array, and copies its elements.
    2. Sort the list in place with Sort(StringComparer.Ordinal). Without the argument, Sort uses the default comparer, which follows the current culture's dictionary rules and would place apple before Zebra. With the ordinal comparer, strings are compared code by code, so Z (code 90) comes before a (code 97).
    3. Return string.Join("\n", sortedLines). The separator is the first argument and goes only between two lines.

    The solution in C#

    class Solution {
        public string SortLines(string[] lines) {
            List<string> sortedLines = new List<string>(lines);
            sortedLines.Sort(StringComparer.Ordinal);
            return string.Join("\n", sortedLines);
        }
    }
    

    The C# details:

    • List<T>.Sort works in place and returns nothing (its return type is void). That is why the call stands on its own line and the list is returned afterwards.
    • Ordinal means code units. Characters are compared by their UTF-16 values, so digits come before uppercase letters, which come before lowercase ones. A shorter string that is a prefix of a longer one comes first, and the empty string is a prefix of everything, so it is always first.
    • Sort is not guaranteed to be stable, but that doesn't matter here: two equal strings are indistinguishable, so their order can't be seen.
    • string.Join accepts a list, because it takes any IEnumerable<string>.

    Complexity

    Time: O(n log n) comparisons for n lines, plus the cost of comparing the strings themselves, which depends on how long their common prefixes are. Space: O(n) for the copied list and for the joined result.

    Edge cases and common mistakes

    • Empty array. The copy is empty, and string.Join of an empty list is "".
    • Case. ["apple", "Zebra", "", "apple"] gives "\nZebra\napple\napple": the empty line first, then Zebra, then both copies of apple.
    • Numbers as text. Ordinal order is textual, so ["100", "20", "3", "10"] becomes "10\n100\n20\n3". Numeric order is a different job.
    • Sorting lines directly. Array.Sort(lines) would reorder the caller's array. After SortLines(arr) the original array still holds its original order, because the method works on a copy.
    • Dropping the comparer. The code still compiles and often looks fine on lowercase test data, but it orders mixed-case input differently.

    Testing

    • ["banana", "apple", "cherry"] gives "apple\nbanana\ncherry".
    • ["apple", "Zebra", "", "apple"] gives "\nZebra\napple\napple".
    • [] 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