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. sortLinessorts a copy of the lines withsort.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
- In
extractField, split the line at commas withstrings.Splitintoparts. It returns one string per piece. - Return the piece at
field - 1. Fields count from 1 but slice positions count from 0, so field 2 isparts[1]. - In
sortLines, createsortedLineswithmakeas a slice of strings as long aslines, so there is room for a copy. - Copy the lines into it with the built-in
copy, destination first. Sorting the copy leaves the caller's slice alone. - Call
sort.SliceStableonsortedLineswith a function of two positionsiandjreturning abool. - Inside it, return whether the key of the line at
iis smaller than the key of the line atj, each found withextractField. - 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.Splitkeeps 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"].makepluscopyis the other way to clone a slice.make([]string, len(lines))creates a slice of that length filled with empty strings, andcopy(dst, src)fills it, copying as many elements as fit. Forgetting themakewould leave a zero-length destination, andcopywould then copy nothing.- Indexing out of range panics.
parts[field-1]would stop the program if a line had fewer fields thanfield. The lesson guarantees that never happens, so there is no check. - The closure captures
fieldandsortedLines. The less function receives only positions, so it reads the lines fromsortedLinesand 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":ybeforewandxbeforez, 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 ofparts[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 putbobfirst. - 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 = 1and an empty slice give"".
