Sorting by a key
Swift does the sorting, and you say what "in order" means by answering one question about two elements.
- Reach for it when
- Order would make the problem easy: near values side by side, smallest first, earliest end first.
- The move
sorted()makes a sorted copy,sort()sorts in place, andsorted { $0.end < $1.end }sorts by whatever you name.- Cost
- Sorting n things costs about n × log n steps: O(n log n).
The idea
I lined a class up for its photo last week, and now the twins' mother wants a word. It seems I promised each twin the place in front of the other.
That's two promises and one place.
We'll come back to it. Five children, five heights: 140, 125, 150, 125, 133. Shortest at the front, please.
heights.sorted(). That's 125, 125, 133, 140, 150.
You didn't move anybody.
Swift did. I don't write a sort. I ask for one.
Did the class move, or did you get a new line?
A new line. sorted() hands back a sorted copy. sort() moves the class itself.
Now the children have names as well. Swift knows which of two numbers is smaller. How does it know which of two children goes first?
It doesn't, so it asks me. It points at two children and asks one question: does the first stand before the second? I say yes or no. For a photo by height, I say yes when the first is shorter.
Tom and Tim are the twins, both 125. Does Tom stand before Tim?
No. He isn't shorter.
Does Tim stand before Tom?
No. Neither stands before the other. That's a tie.
Then who's in front?
Whoever was in front already. Swift leaves a tie as it found it. If the photo wants twins in order of their names, I have to say so: height first, and for the same height, the name.
And if you'd said yes both times, to keep the peace?
Then I've promised each twin the place in front of the other. Swift can't keep both promises, and it won't tell me which one it broke.
I'd like their mother to hear that from you.
That is the whole tool: Swift does the sorting, and you answer one question about two elements at a time.
The shape
A child has a name and a height:
/// One child in the class.
struct Child {
let name: String
let height: Int
}This is what you know by heart:
/// The class in a line for its photo, shortest first.
/// Children of the same height go by name.
func lineUp(_ children: [Child]) -> [Child] {
return children.sorted { first, second in
if first.height != second.height {
return first.height < second.height // the key decides
}
return first.name < second.name // a tie on the key: the name decides
}
}It has four parts, and each is there for a reason.
sorted. Swift does the sorting. It hands back a new array, in order, and leaveschildrenas it was.- The closure. What is between the braces is your answer to the one question: does
firststand beforesecond? It hands backtrueorfalse. - The key. The first comparison is on what the line is ordered by: here,
height. Theifasks whether the two keys differ, and when they do, the key decides, whichever way that goes. It decides with<, never<=: a child does not stand before another of the same height. - The tie. When the keys are equal, the closure goes on to the next thing: here,
name.
Leave the tie out and the closure is one comparison. Swift lets you write that short:
/// Shortest first, with nothing said about a tie: Swift leaves a tie as it found it.
func lineUpByHeightAlone(_ children: [Child]) -> [Child] {
return children.sorted { $0.height < $1.height }
}$0 is the first child and $1 is the second. Both closures are right, for different problems: what a problem says about a tie tells you which one it wants. Learn the long one. The short one is its first comparison on its own.
Watch it run
The class sits in this order: Mia (140), Tom (125), Zoe (150), Tim (125) and Lou (133). Here is every question Swift asked the closure of lineUp, and the answer it got.
| first | second | does first stand before second? |
|---|---|---|
| Tom, 125 | Mia, 140 | yes |
| Zoe, 150 | Mia, 140 | no |
| Tim, 125 | Zoe, 150 | yes |
| Tim, 125 | Mia, 140 | yes |
| Tim, 125 | Tom, 125 | yes |
| Lou, 133 | Zoe, 150 | yes |
| Lou, 133 | Mia, 140 | yes |
| Lou, 133 | Tom, 125 | no |
The line is Tim, Tom, Lou, Mia, Zoe.
Never mind why Swift asked in this order: another version of Swift may ask differently. Look at what it asked: two children at a time, and the same question every time. In the first row it asked about Tom and then Mia, though Mia sits first: first and second are whichever two Swift is holding.
Now look at the fifth row. Tim and Tom are the same height, so the key had nothing to say, and the names decided: Tim comes before Tom in the alphabet, so the answer was yes. With the short closure the answer would have been no, and the line would be Tom, Tim, Lou, Mia, Zoe: the twins as they came.
Step by step
Sort numbers upwards, then downwards
Numbers know their own order, so there is no closure to write yet. This step has three small parts.
Upwards.
/// The numbers, smallest first. `numbers` itself is not changed.
func upwards(_ numbers: [Int]) -> [Int] {
return numbers.sorted()
}What is new: sorted() hands back a new array with the smallest number first. For the five heights it gives [125, 125, 133, 140, 150].
Downwards.
/// The numbers, largest first.
func downwards(_ numbers: [Int]) -> [Int] {
return numbers.sorted(by: >)
}What is new: by: is where the answer to the one question goes, and for numbers it can be one character. > says the first stands before the second when it is bigger, so the largest comes first: [150, 140, 133, 125, 125].
In place.
/// Sorts `numbers` itself, largest first. Nothing is handed back.
func sortDownwards(_ numbers: inout [Int]) {
numbers.sort(by: >)
}What is new: sort does the same work on the array itself and hands nothing back: it leaves the five heights as [150, 140, 133, 125, 125]. It needs an array it may change: a var, or an inout parameter as here. A plain parameter is a constant, so numbers.sort() would not compile inside upwards. In most functions sorted() is the one you want.
A sort is not free: to put 1,000 scrambled numbers in order, Swift asked its question 20,017 times, where one pass looks at each number once.
The smallest and the largest without sorting
To find the shortest child you do not line up the class. You walk past it once.
/// How far apart the smallest and the largest number are.
/// `nil` when there are no numbers.
func spread(_ numbers: [Int]) -> Int? {
if let smallest = numbers.min(), let largest = numbers.max() {
return largest - smallest
}
return nil
}What is new: min() and max(), which each find one number in one pass and hand it back as an optional.
For the same 1,000 numbers, min() asked the question 999 times, against 20,017 for the sort. The lesson "Best so far" writes that walk by hand.
The optional is there because an empty array has no smallest number, and Swift will not make one up: min() of an empty array is nil. Even a real answer comes wrapped: for the five heights, min() prints as Optional(125). Unwrap it with if let, as in "A dictionary with a default". For the five heights spread gives 25, which is 150 less 125.
Sort words by length
Words have an order of their own, the alphabet, and words.sorted() uses it. To order them by length, Swift needs your answer. This step has three small parts.
The key.
/// The words, shortest first. Words of the same length stay in the order they came in.
func byLength(_ words: [String]) -> [String] {
return words.sorted { $0.count < $1.count }
}What is new: the closure. $0 is the first word and $1 is the second, and it says yes when the first is shorter. It compares a key, each word's count, in place of the words themselves. For pear, fig, plum and kiwi it gives ["fig", "pear", "plum", "kiwi"].
Three of those words have four letters. Asked about any two of them, the closure says no both ways round: a tie. Swift leaves a tie in the order it found it, and that is a promise. Its documentation says the sort is guaranteed to be stable, which is the name for a sort that does this. So pear, plum and kiwi stay as they came.
Who goes first in a tie.
/// The words, shortest first. Words of the same length go in alphabetical order.
func byLengthThenAlphabet(_ words: [String]) -> [String] {
return words.sorted { first, second in
if first.count != second.count {
return first.count < second.count
}
return first < second
}
}What is new: a second comparison, reached only when the first has nothing to say. It is the shape, with count as the key and the alphabet to settle a tie. The same words now give ["fig", "kiwi", "pear", "plum"].
The twins' bug.
func byLengthWithABug(_ words: [String]) -> [String] {
return words.sorted { $0.count <= $1.count } // wrong: a tie is told yes both ways
}For the same four words this gives ["fig", "kiwi", "plum", "pear"]: the four-letter words have come out backwards.
What is new is the rule a sort relies on: nothing stands before its equal. <= says yes for a tie, both ways round, so pear was told to stand before plum, and plum before pear. With the rule broken, the promise about ties is off, and what comes back is whatever this version of Swift happens to do.
Sort pairs by their second number
A pair is an array of two numbers. Take meetings, each a [start, end]. Sorting them by their second number puts first the meeting that ends first.
/// The meetings, earliest end first. Each meeting is `[start, end]`.
/// Meetings that end together go by their starts.
func byEnd(_ meetings: [[Int]]) -> [[Int]] {
return meetings.sorted { first, second in
if first[1] != second[1] {
return first[1] < second[1] // [1] is the end: the key
}
return first[0] < second[0] // [0] is the start: it settles a tie
}
}What is new: the key is one part of each element, read with a subscript. first[1] is the end of the first meeting. For the meetings 9 to 12, 10 to 11, 8 to 11 and 13 to 14 this gives [[8, 11], [10, 11], [9, 12], [13, 14]]. Two meetings end at 11, and the one that starts at 8 goes first, because [0] settles a tie. If a meeting were a struct, the key would be first.end, as it was first.height for a child.
Latest first.
/// The meetings, latest end first.
/// Meetings that end together still go by their starts, earliest first.
func byLatestEnd(_ meetings: [[Int]]) -> [[Int]] {
return meetings.sorted { first, second in
if first[1] != second[1] {
return first[1] > second[1] // the key goes downwards
}
return first[0] < second[0] // the tie still goes upwards
}
}What is new: each comparison has its own direction. The key goes downwards with >, and the tie still goes upwards with <: [[13, 14], [9, 12], [8, 11], [10, 11]]. That is why you do not sort upwards and then turn the array round with reversed(). Turning it round turns the ties round too: [[13, 14], [9, 12], [10, 11], [8, 11]], with 10 to 11 ahead of 8 to 11.
Sort positions by the values they point at
Sort the heights and you learn that the shortest child is 125 tall. You no longer know which desk that child sits at. So leave the heights where they are, and sort the positions.
/// The positions of `numbers`, in order of the numbers they point at, smallest first.
/// Positions that point at equal numbers go in their own order.
func positionsByValue(_ numbers: [Int]) -> [Int] {
let positions = Array(numbers.indices)
return positions.sorted { first, second in
if numbers[first] != numbers[second] {
return numbers[first] < numbers[second] // compare what they point at
}
return first < second // a tie: the earlier position
}
}What is new: the array you sort is not the array you compare. positions starts as [0, 1, 2, 3, 4]. The closure is handed two positions, and looks through each at the number it points at: numbers[first]. For the five heights the answer is [1, 3, 4, 0, 2]: the shortest child is at position 1, the next at position 3, and the tallest at position 2.
Positions 1 and 3 both point at 125. The tie goes to the earlier position, and the last line says so.
Pair two arrays with zip and sort the pairs by one of them
Here the class comes as two arrays: names[i] is the name of the child whose height is heights[i]. Sort heights alone and that stops being true: names[0] is still Mia, beside a height of 125 that is not hers. zip fastens each name to its height first, so the two travel together.
/// The names, shortest child first. `heights[i]` is the height of `names[i]`.
/// Children of the same height go by name.
func namesByHeight(_ names: [String], _ heights: [Int]) -> [String] {
let children = zip(names, heights).sorted { first, second in
if first.1 != second.1 {
return first.1 < second.1 // .1 is the height: the key
}
return first.0 < second.0 // .0 is the name: it settles a tie
}
var inOrder: [String] = []
for child in children {
inOrder.append(child.0)
}
return inOrder
}What is new: zip(names, heights) makes one pair for each position: [("Mia", 140), ("Tom", 125), ("Zoe", 150), ("Tim", 125), ("Lou", 133)]. Each pair is a tuple, and its two parts are called .0 and .1: here the name and the height. After that it is the shape again, with .1 as the key and .0 to settle a tie. The loop at the end takes the names back out: ["Tim", "Tom", "Lou", "Mia", "Zoe"].
zip stops when the shorter array runs out. Give it the five names and only two heights and it makes [("Mia", 140), ("Tom", 125)]: the other children are dropped, and nothing warns you. Give it two arrays of the same length.
Sort the characters of a string
A string is a line of characters, so sorted() works on it as well.
/// The letters of `word` in alphabetical order.
func sortedLetters(_ word: String) -> String {
return String(word.sorted())
}What is new: what comes back is an array of characters, not a string. "swift".sorted() is ["f", "i", "s", "t", "w"], and String makes a string of it again: fistw. It is the trip from "A string as an array of characters": out to an array, do the work, and back.
What goes wrong
Answering with <=. The closure must say no for a tie, both ways round. <= says yes, and the ties come back in an order nobody promised: ["fig", "kiwi", "plum", "pear"] for pear, fig, plum and kiwi. Compare with < or >.
Saying nothing about a tie. { $0.count < $1.count } leaves a tie as it came. That is right when the problem says so, and wrong when it wants the alphabet: ["fig", "pear", "plum", "kiwi"] where ["fig", "kiwi", "pear", "plum"] was wanted. Read what the problem says about a tie before you write the closure.
Letting the tie-break answer for a key that lost. A closure that starts if first.count < second.count { return true } and goes straight on to the alphabet has forgotten that the first word may be longer. Asked about apple and fig, it finds that apple is not shorter, goes on to the alphabet, and says yes, so the longer word comes out first: ["apple", "fig"]. The if in the shape asks whether the keys differ, and when they do, the key answers.
Throwing the copy away. heights.sorted() on a line of its own makes a sorted copy and drops it. The array is as it was: [140, 125, 150, 125, 133]. Swift warns that the result is unused, and the warning is right. Keep the copy, or call sort().
Unwrapping min() with !. numbers.min()! stops the program when the array is empty: min() is nil then, and there is nothing to unwrap. Use ! only when the problem promises at least one element. Otherwise use if let, and decide what an empty array should give.
Capital letters. Swift orders strings by the numbers behind their characters, and every capital letter comes before every small one: ["pear", "Zebra", "apple"].sorted() is ["Zebra", "apple", "pear"]. It shows only when some words have capitals and others do not, and the problems here keep to one or the other.
Say it back
What is the difference between sorted() and sort()?
Show the answerHide the answer
sorted() hands back a sorted copy and leaves the array alone. sort() sorts the array itself, which must be a var, and hands nothing back.
What is the one question the closure answers?
Show the answerHide the answer
Does the first stand before the second? It answers yes or no, about two elements at a time, and Swift does the rest.
Two elements tie on the key. What must the closure answer, and where do they end up?
Show the answerHide the answer
No, both ways round. Swift then leaves them in the order they came in. If the problem wants a tie settled another way, the closure goes on to compare the next thing.
You want only the smallest number. Why not sort, and what does min() hand back?
Show the answerHide the answer
A sort does far more work than the one pass that min() takes. min() hands back an optional, because an empty array has no smallest number.
You sort positions in place of values. What does the closure compare, and what have you kept?
Show the answerHide the answer
It compares the values the positions point at: numbers[first] and numbers[second]. The answer still says where each value came from.
How did Harper promise each twin the place in front of the other?
Show the answerHide the answer
She answered the one question with <=. Does Tom stand before Tim? Yes, because 125 is less than or equal to 125. Does Tim stand before Tom? Yes again. For a tie the answer is no both ways round: compare with <, and when the problem says who goes first in a tie, compare that next.
Practise
These are this lesson's problems in the Orithms app, in the order they come.
| Problem | Level | |
|---|---|---|
| 1 | Smallest first | Easy |
| 2 | Largest first | Easy |
| 3 | Sort the array itself | Easy |
| 4 | How far apart are the smallest and the largest? | Easy |
| 5 | Shortest word first | Easy |
| 6 | Shortest first, and a tie by the alphabet | Easy |
| 7 | Each twin was promised the place in front | Easy |
| 8 | Meetings in order of when they end | Easy |
| 9 | Latest end first, earliest start for a tie | Easy |
| 10 | Positions, in order of the numbers they point at | Easy |
| 11 | The names, shortest child first | Easy |
| 12 | A word's letters in order | Easy |
These problems are done in the Orithms Mac app.
Every piece of code and every number in a lesson comes from a file that was compiled and run.