Lists: Sorting
● Beginner3 min
sort() gives a sorted copy; sort_by sorts by a key; reverse() turns a list around.
type Player {
name: String
score: Int
}
fn main() {
const xs = [3, 1, 4, 1, 5]
print(xs.sort())
print(xs.sort().reverse())
print(xs)
print(xs.max() ?? 0)
const players = [Player(name: "Asha", score: 72), Player(name: "Ravi", score: 90)]
print(players.sort_by(.score).reverse().map(.name))
}The program ran and printed:
kavach run sort.kav
[1, 1, 3, 4, 5][5, 4, 3, 1, 1][3, 1, 4, 1, 5]5["Ravi", "Asha"]
Each gives a new list and leaves the original as it was: xs is still [3, 1, 4, 1, 5]. sort_by(.score) sorts players by their score, keeping equal scores in their order.
How text, floats and records sort, sorting by two keys, and which algorithm runs: see Sorting.