Start learning free

LESSON 24 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Sort -k in Go: Stable Sort by a Key Column

Practice Read the full explanation

Build the next version of the Unix sort command, this time with the -k flag baked in. Each input line is comma-separated and is guaranteed to have at least field fields (a field may be empty, as in "a,,c"). Given a 1-indexed field number, sort the lines stably by the value at that field, compared as strings by character code, and return the original lines joined by newlines (\n). Lines whose fields are equal keep their original relative order. This matches the real command sort -t, -k N,N -s in the C locale. If the list is empty, return the empty string.

Function signature:

func sortLines(lines []string, field int) string

Example:

Input: field = 2, lines = ["alice,30", "bob,25", "carol,40"]

Output: "bob,25\nalice,30\ncarol,40"

When printed:
bob,25
alice,30
carol,40

Use sort.SliceStable (NOT sort.Slice, which isn't guaranteed stable). Write a helper that extracts the field with strings.Split, compare those keys in the less function, and join the result with strings.Join.

func extractField(line string, field int) string {
    parts := strings.Split(line, ",")
    return parts[field-1]
}


The full solution:
func extractField(line string, field int) string {
    parts := strings.Split(line, ",")
    return parts[field-1]
}

func sortLines(lines []string, field int) string {
    sortedLines := make([]string, len(lines))
    copy(sortedLines, lines)
    sort.SliceStable(sortedLines, func(i, j int) bool {
        return extractField(sortedLines[i], field) < extractField(sortedLines[j], field)
    })
    return strings.Join(sortedLines, "\n")
}

STEP 1 OF 7
    Ctrl + Enter to check

    GO · PROJECTS: COMMAND-LINE TOOLS

    Sort V4 in Go, explained

    Problem overview

    This version of sort has the -k flag built in. Each line is comma-separated and has at least field fields; a field may be empty, as in "a,,c". The function sortLines(lines []string, field int) sorts the lines by the value in the 1-indexed column field, compared as strings by character code. It returns the original lines, joined by "\n".

    The sort is stable: lines whose key fields are equal keep their input order. This matches sort -t, -k N,N -s in the C locale. An empty slice gives the empty string.

    For field = 2 and ["alice,30", "bob,25", "carol,40"], the keys are "30", "25" and "40", so the result is "bob,25\nalice,30\ncarol,40".

    Approach: sort whole lines, compare only their keys

    The lines stay whole in the output, but the order depends on one column. The lesson splits the work in two:

    • A helper, extractField, takes a line and a field number and returns that column's text.
    • sortLines sorts a copy of the lines with sort.SliceStable, and its less function compares the keys of the two lines with <.

    Stability does the tie-breaking for free. When two lines have equal keys, the less function says neither goes first, and SliceStable keeps them in their input order.

    Step by step

    1. In extractField, split the line at commas with strings.Split into parts. It returns one string per piece.
    2. Return the piece at field - 1. Fields count from 1 but slice positions count from 0, so field 2 is parts[1].
    3. In sortLines, create sortedLines with make as a slice of strings as long as lines, so there is room for a copy.
    4. Copy the lines into it with the built-in copy, destination first. Sorting the copy leaves the caller's slice alone.
    5. Call sort.SliceStable on sortedLines with a function of two positions i and j returning a bool.
    6. Inside it, return whether the key of the line at i is smaller than the key of the line at j, each found with extractField.
    7. Join the sorted copy with "\n" and return it.

    The solution in Go

    func extractField(line string, field int) string {
        parts := strings.Split(line, ",")
        return parts[field-1]
    }
    
    func sortLines(lines []string, field int) string {
        sortedLines := make([]string, len(lines))
        copy(sortedLines, lines)
        sort.SliceStable(sortedLines, func(i, j int) bool {
            return extractField(sortedLines[i], field) < extractField(sortedLines[j], field)
        })
        return strings.Join(sortedLines, "\n")
    }
    

    Go details to notice:

    • strings.Split keeps empty pieces. strings.Split("a,,c", ",") gives ["a" "" "c"], so an empty field is simply the empty string, and field 2 of that line is "". A line with no comma, such as "abc", splits into a single piece ["abc"].
    • make plus copy is the other way to clone a slice. make([]string, len(lines)) creates a slice of that length filled with empty strings, and copy(dst, src) fills it, copying as many elements as fit. Forgetting the make would leave a zero-length destination, and copy would then copy nothing.
    • Indexing out of range panics. parts[field-1] would stop the program if a line had fewer fields than field. The lesson guarantees that never happens, so there is no check.
    • The closure captures field and sortedLines. The less function receives only positions, so it reads the lines from sortedLines and the column number from the enclosing function's parameter.
    • Strings compare by bytes. < on strings is the character-code order the lesson asks for, so digits compare as text, not as numbers.

    Complexity

    Time: O(n log n) comparisons for n lines. Every comparison splits two lines, so its cost grows with line length. The solution re-splits on each comparison rather than extracting each key once, which is simple and fine for small inputs. Extracting the keys up front would avoid the repeated work.

    Space: O(n) for the copy and the output, plus the temporary slices that Split creates during comparisons.

    Edge cases and common mistakes

    • Digits compare as text. With field = 2, ["p,100", "q,20", "r,3"] comes back unchanged, because "100" < "20" < "3" as strings. Numeric sorting is a different version of the tool.
    • Ties keep input order. With field = 2, ["x,b", "y,a", "z,b", "w,a"] gives "y,a\nw,a\nx,b\nz,b": y before w and x before z, as in the input.
    • Empty fields sort first. With field = 2, ["a,b,c", "a,,c", "a,a,c"] gives "a,,c\na,a,c\na,b,c".
    • Off-by-one on the field. Using parts[field] instead of parts[field-1] sorts by the wrong column and can panic on the last one.
    • Sorting by the whole line. Comparing the full lines would give a different order whenever the key column and the line order disagree. With field = 2, the lines "alice,30" and "bob,25" must put bob first.
    • Using sort.Slice. It does not promise to keep ties in input order.

    Testing

    • field = 2, ["alice,30", "bob,25", "carol,40"] gives "bob,25\nalice,30\ncarol,40".
    • field = 1, the same lines, gives "alice,30\nbob,25\ncarol,40".
    • field = 2, ["x,b", "y,a", "z,b", "w,a"] gives "y,a\nw,a\nx,b\nz,b".
    • field = 2, ["a,b,c", "a,,c", "a,a,c"] gives "a,,c\na,a,c\na,b,c".
    • field = 2, ["p,100", "q,20", "r,3"] gives "p,100\nq,20\nr,3".
    • field = 1 and an empty slice give "".
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free