如何在Rust中对向量排序?

How to sort a vector in Rust?

目前推荐的对向量中的值进行排序的方法是什么?


可变元素的总顺序为sort

因为Vec< T >实现了DerefMut<[T]>,所以可以直接在向量上调用此方法,因此vector.sort()可以工作。


虽然上面提出的解决方案可以对整数向量进行排序,但我在对浮点向量进行排序时遇到了问题。

最简单的解决方案是使用quickersort板条箱,该板条箱也可以对浮标进行排序。
quickersort板条箱还可以对其他任何类型的向量进行排序,还可以实现使用比较进行排序的方法(sort_by)。

以下是Rust代码:

1
2
3
4
5
6
7
8
9
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