What is the currently recommended method for sorting values in a vector?
3 Answers
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
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.