Maxim Sloyko
Maxim Sloyko

Reputation: 15866

How to sort a vector in Rust?

What is the currently recommended method for sorting values in a vector?

Upvotes: 164

Views: 110648

Answers (3)

at54321
at54321

Reputation: 11708

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 as f64, 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.

Upvotes: 18

Salvatore Cosentino
Salvatore Cosentino

Reputation: 7220

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

Upvotes: -1

Chris Morgan
Chris Morgan

Reputation: 90742

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.

Upvotes: 152

Related Questions