Start learning free

LESSON 23 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort -n in Go: Numeric Sort with sort.SliceStable

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:

func sortLines(lines []string) string

Example:

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

Output: "3\n10\n20\n100"

When printed:
3
10
20
100

Sort with sort.SliceStable and a less-function that parses each string via strconv.Atoi, then join the result with strings.Join.

The full solution:
func sortLines(lines []string) string {
    sortedLines := append([]string{}, lines...)
    sort.SliceStable(sortedLines, func(i, j int) bool {
        ai, _ := strconv.Atoi(sortedLines[i])
        aj, _ := strconv.Atoi(sortedLines[j])
        return ai < aj
    })
    return strings.Join(sortedLines, "\n")
}

STEP 1 OF 7
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Sort V3 in Go, explained

    Problem overview

    This version of sort has the -n flag built in. Every line is the text of an integer that fits in 32 bits: an optional leading -, no leading +, and leading zeros such as "007" are allowed. sortLines sorts the lines by numeric value, ascending, and returns the original strings joined by "\n".

    Lines with the same value keep their input order, which is a stable sort. (The real sort -n breaks ties by comparing the text, but this version does not.) An empty slice gives the empty string.

    For ["100", "20", "3", "10"] the result is "3\n10\n20\n100". Sorting as text would put "100" first, since 1 is smaller than 2 and 3 as a character. Sorting as numbers puts 3 first.

    Approach: compare numbers, return the strings

    The output must contain the original strings, so "007" stays "007". The numbers are needed only to decide the order. The plan is to sort a copy of the lines with a less function that converts the two lines it is asked about to int and compares them.

    Two ties need thought. "7", "007" and "07" are all the number 7, and they must come out in the order they came in. sort.Slice does not promise that, but sort.SliceStable does: it takes the same arguments and keeps equal elements in their original relative order. Equal here means the less function says neither one goes before the other, which is exactly the case for equal numbers.

    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, so the caller's slice is untouched.
    3. Call sort.SliceStable on the copy with a function of two positions i and j that returns a bool. Write the closing }) immediately and fill in the body.
    4. Parse the line at i with strconv.Atoi into ai. Atoi returns the number and an error; the blank identifier _ discards the error.
    5. Parse the line at j into aj the same way.
    6. Return ai < aj. True means the line at i goes first, which gives ascending order.
    7. Join the sorted copy with "\n" and return it.

    The solution in Go

    func sortLines(lines []string) string {
        sortedLines := append([]string{}, lines...)
        sort.SliceStable(sortedLines, func(i, j int) bool {
            ai, _ := strconv.Atoi(sortedLines[i])
            aj, _ := strconv.Atoi(sortedLines[j])
            return ai < aj
        })
        return strings.Join(sortedLines, "\n")
    }
    

    Go details to notice:

    • strconv.Atoi returns two values. Go has no exceptions: a function that can fail returns an error as a second value. ai, _ := ... keeps the number and throws the error away. That is safe here because every line is guaranteed to be a valid integer. For input like "12a", Atoi returns 0 together with an error saying parsing "12a": invalid syntax, so ignoring errors on untrusted input would silently turn bad lines into zeros.
    • Leading zeros and signs are fine. Atoi("007") is 7 and Atoi("-12") is -12. The number is used only for comparing: the output keeps the original text.
    • int is 64 bits here, so any 32-bit value converts and compares without overflow.
    • The less function reads the slice being sorted. The positions i and j refer to sortedLines as it is rearranged during the sort, so the function must read sortedLines, not lines.
    • Stability matters only for ties. The comparison ai < aj is false in both directions for equal numbers, and SliceStable then leaves those elements in input order.

    Complexity

    Time: O(n log n) comparisons for n lines, and each comparison parses two short strings. The solution parses again on every comparison instead of once per line. For a lesson-sized input that is fine, and it keeps the code short. Parsing each line once into a separate slice of numbers would avoid the repeated work.

    Space: O(n) for the copy and the joined output.

    Edge cases and common mistakes

    • Sorting as text. sort.Strings on ["100", "20", "3", "10"] gives [10 100 20 3]. Numeric order needs the conversion.
    • Negative numbers. ["-5", "3", "-20", "0"] gives "-20\n-5\n0\n3". As text, - would mislead the order, but as numbers it works.
    • Equal values with different text. ["007", "7", "07", "6"] gives "6\n007\n7\n07", and ["7", "007", "07"] comes back unchanged. The tied lines keep their input order.
    • Using sort.Slice. It may reorder tied lines, so a test with equal numbers can fail unpredictably. Use SliceStable.
    • Returning numbers instead of the original text. The result must contain "007", not "7".
    • Empty input. An empty slice gives "".

    Testing

    • ["100", "20", "3", "10"] gives "3\n10\n20\n100".
    • ["-5", "3", "-20", "0"] gives "-20\n-5\n0\n3".
    • ["007", "7", "07", "6"] gives "6\n007\n7\n07".
    • ["7", "007", "07"] gives "7\n007\n07".
    • 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