typestar

Parallel sorting in Rust

par_sort splits, sorts and merges — worth it once the slice is large.

use rayon::prelude::*;

fn main() {
    let mut values: Vec<u64> = (0..200_000)
        .map(|n| (n * 2_654_435_761) % 100_000)
        .collect();

    values.par_sort_unstable();
    println!("{:?}", &values[..5]);

    let mut words = vec!["kiwi", "fig", "banana", "plum"];
    words.par_sort_by_key(|w| w.len());
    println!("{:?}", words);
}

How it works

  1. par_sort_unstable is the fastest when equal items are alike.
  2. par_sort_by_key takes the same key closure as the serial form.
  3. Small slices fall back to a serial sort automatically.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
307
Tokens
113
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 65 seconds.

Type this snippet

Step 3 of 3 in Parallel iterators, step 3 of 9 in Data parallelism with rayon.

← Previous Next →