How to sort a vector in Rust

Created
Modified

Using sort Method

The sort(&mut self) method sorts the slice. This sort is stable (i.e., does not reorder equal elements) and O(n * log(n)) worst-case. For example,

fn main() {
  let mut v = [3, -5, 2, 6, 1];
  v.sort();
  println!("{:?}", v);

  let mut s = ["b", "d", "c", "a"];
  s.sort();
  println!("{:?}", s);
}
[-5, 1, 2, 3, 6]
["a", "b", "c", "d"]

Using sort_by Method

The sort_by(&mut self, compare: F) method sorts the slice with a comparator function. The comparator function must define a total ordering for the elements in the slice. If the ordering is not total, the order of the elements is unspecified. For example,

fn main() {
  let mut v = [5, 4, 1, 3, 2];
  v.sort_by(|a, b| a.cmp(b));
  println!("{:?}", v);

  let mut s = ["b", "d", "c", "a"];
  s.sort_by(|a, b| b.cmp(a));
  println!("{:?}", s);
}
[1, 2, 3, 4, 5]
["d", "c", "b", "a"]

Related Tags

#sort# #vector#