How to sort a vector in Rust?
RustRust Problem Overview
What is the currently recommended method for sorting values in a vector?
Rust Solutions
Solution 1 - 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.
Solution 2 - Rust
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.
Solution 3 - Rust
While the solutions proposed above can sort vectors of integers I had problems in sorting vectors of floats.
The simplest solution was to use the quickersort crate, which can also sort floats. The quickersort crate can also sort other vectors of any type and also implements methods to sort using comparisons (sort_by).
Following is the Rust code:
extern crate quickersort;
//let's create the vector with the values
let mut vals = Vec::new();
vals.push(31.2);
vals.push(31.2);
vals.push(10.0);
vals.push(100.4);
vals.push(4.1);
quickersort::sort_floats(&mut vals[..]); // sort the vector