Sorting in Julia
by= picks the key, rev= the direction, sortperm the indices.
sessions = [("M31", 300), ("M42", 120), ("M13", 240)]
# sort takes by= for the key and rev= for the direction.
by_time = sort(sessions, by = s -> s[2], rev = true)
println(by_time)
names = sort(first.(sessions))
println(names)
# sortperm gives the ordering as indices, to reuse elsewhere.
order = sortperm(sessions, by = s -> s[2])
println("Shortest first: ", [sessions[i][1] for i in order])
println("Is it sorted? ", issorted(names))
How it works
sort(xs, by = s -> s[2], rev = true)ranks by a field.first.(sessions)broadcasts an accessor before sorting.sortpermreturns the ordering for use on other arrays.
Keywords and builtins used here
forintrue
The run, in numbers
- Lines
- 13
- Characters to type
- 438
- Tokens
- 112
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 103 seconds.
Step 3 of 3 in Macros & formatting, step 24 of 27 in Language basics.