How to sort a vector in Rust?
A mutable slice of elements with a total ordering has a sort
method.
Because Vec<T>
implements DerefMut<[T]>
, you can call this method directly on a vector, so vector.sort()
works.
To sort a vector v
, in most cases v.sort()
will be what you need.
If you want to apply a custom ordering rule, you can do that via v.sort_by()
. That includes cases where you want to sort values that:
- don't implement
Ord
(such asf64
, most structs, etc); - do implement
Ord
, but you want to apply a specific non-standard ordering rule.
Also note that sort()
and sort_by()
use a stable sorting algorithm (i.e., equal elements are not reordered). If you don't need a stable sort, you can use sort_unstable()
/ sort_unstable_by()
, as those are generally a bit faster and use less memory.