Mastodon How to sort a vector in Rust

How to sort a vector in Rust

sort

The simplest method (no pun intended) to sort a vector in Rust is to use sort.

fn main() {
    let mut v = vec![3, 2, 90, 78, 64, 32, 1, -10, 10, 10000];
    v.sort();
    println!("{:?}", v);
}
[-10, 1, 2, 3, 10, 32, 64, 78, 90, 10000]

Please note that this method requires your type to implement the Ord trait.

sort_by

Alternatively, if your type does not implement Ord, you can use the sort_by method.

use std::cmp::Ordering;

#[derive(Debug)]
struct Point {
    x: i64,
    y: i64,
}

fn main() {
    let mut v = vec![
        Point { x: 3, y: 2 },
        Point { x: 90, y: 78 },
        Point { x: 64, y: 32 },
        Point { x: 1, y: -10 },
        Point { x: 10, y: 10000 },
    ];
    v.sort_by(|a, b| {
        if a.x < b.x {
            Ordering::Less
        } else if a.x == b.x {
            Ordering::Equal
        } else {
            Ordering::Greater
        }
    });
    println!("{:?}", v);
}
[Point { x: 1, y: -10 }, Point { x: 3, y: 2 }, Point { x: 10, y: 10000 }, Point { x: 64, y: 32 }, Point { x: 90, y: 78 }]

par_sort

If you want to sort items in parallel, you can also use par_sort and par_sort_by from the rayon crate.

use rayon::prelude::*;

fn main() {
    let mut v = vec![3, 2, 90, 78, 64, 32, 1, -10, 10, 10000];
    v.par_sort();
    println!("{:?}", v);
}

sort_unstable

Finally, there are the sort_unstable, sort_unstable_by, par_sort_unstable_by, and par_sort_unstable (the fastest), if you need absolute performance.

fn main() {
    let mut v = vec![3, 2, 90, 78, 64, 32, 1, -10, 10, 10000];
    v.sort_unstable();
    println!("{:?}", v);
}

The code is on GitHub

As usual, you can find the code on GitHub: github.com/skerkour/kerkour.com (please don’t forget to star the repo 🙏)

Join the private club where I share exclusive tips and stories about programming, hacking and entrepreneurship. 1 message / week.
I hate spam even more than you do. I'll never share your email, and you can unsubscribe at any time.

Want to learn Rust and offensive security? Take a look at my book Black Hat Rust. All early-access supporters get a special discount and awesome bonuses: https://academy.kerkour.com/black-hat-rust?coupon=BLOG.
Warning: this offer is limited in time!


Tags: rust, programming, tutorial

Related posts