Problem overview
The fourth version of the sort tool adds the -k flag. sortLines(_ lines: [String], _ field: Int) -> String receives comma-separated lines and a 1-based field number. It sorts the lines stably by the text in that field, compared as strings by character code, and returns the original lines joined with "\n". Every line has at least field fields, and a field may be empty, as in "a,,c".
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". An empty list gives "".
Approach: sort with a key-extracting closure
The previous version compared parsed numbers inside a sort closure. This one has the same shape: keep whole lines in the array, and let the closure decide the order by looking at one field of each line. The key of a line is what you get by splitting it at the commas and taking the piece at position field - 1. The fields count from 1, but array positions count from 0.
Because keys are compared as text, "10" sorts before "9". For ["a,9", "b,10"] with field 2 the result is "b,10\na,9". Only the key comparison matters, and ties keep input order.
Step by step
- Copy
linesinto avarnamedsortedLines. Sorting the copy leaves the caller's array unchanged. - Sort in place with a closure that returns whether the key of
$0is smaller than the key of$1. Each key issplit(separator: ",", omittingEmptySubsequences: false)[field - 1]. - Return
sortedLines.joined(separator: "\n"). The lines come out unchanged, only reordered.
The solution in Swift
func sortLines(_ lines: [String], _ field: Int) -> String {
var sortedLines = lines
sortedLines.sort { $0.split(separator: ",", omittingEmptySubsequences: false)[field - 1] < $1.split(separator: ",", omittingEmptySubsequences: false)[field - 1] }
return sortedLines.joined(separator: "\n")
}
Details that matter:
- Why
omittingEmptySubsequences: false. By defaultsplitthrows away empty pieces."a,,c".split(separator: ",")has 2 pieces, while withomittingEmptySubsequences: falseit has 3, and the middle one is empty. Without the argument, an empty field would shift every later field one place to the left, andfield - 1would point at the wrong piece or past the end. - Substrings.
splitreturnsSubstringvalues, slices of the original line, not new strings.Substringvalues compare with<just as strings do, so the closure needs no conversion. - Empty keys sort first. An empty string is smaller than any other. With
["x,b", "y,", "z,a"]and field 2, the result is"y,\nz,a\nx,b". - Stability. Lines with equal keys must keep their input order. The standard library's documentation doesn't promise a stable
sort, but the current implementation is stable, and the lesson relies on it. With["b,1", "a,1", "c,0", "d,1"]and field 2, the result is"c,0\nb,1\na,1\nd,1": the three lines with key"1"stay in their original order. - Splitting on every comparison. The closure runs for each comparison and splits both lines each time. That is simple and fits the small inputs here.
Complexity
Time: O(n log n) comparisons for n lines. Each comparison splits two lines, which costs time proportional to their length, on top of comparing the keys. Space: O(n) for the copy and the output, plus the temporary pieces of the two lines being compared.
Edge cases and common mistakes
- Off by one. Using
[field]instead of[field - 1]sorts by the wrong column and can fail on the last one, because the index is past the end. - Dropping empty fields. Leaving out
omittingEmptySubsequences: falseis the common bug for lines like"a,,c". - Numbers compared as text. The keys are strings, so
"10"comes before"9". The key column is not parsed in this version. - Different from sorting whole lines. Sorting by field 1 of
["alice,30", "bob,25", "carol,40"]gives"alice,30\nbob,25\ncarol,40"; only that field decides. - One line and empty list. A single line stays as it is, and an empty list gives
"".
Testing
["alice,30", "bob,25", "carol,40"]with field 2 gives"bob,25\nalice,30\ncarol,40".- The same lines with field 1 give
"alice,30\nbob,25\ncarol,40". ["x,b", "y,", "z,a"]with field 2 gives"y,\nz,a\nx,b".["b,1", "a,1", "c,0", "d,1"]with field 2 gives"c,0\nb,1\na,1\nd,1".["a,9", "b,10"]with field 2 gives"b,10\na,9".[]with field 1 gives"".
