#quick-sort #select #nth-element #quickselect #pdqsort

no-std pdqselect

Selects the kth smallest element of a slice, based on Orson Peters's Pattern Defeating Quickselect

2 releases

0.1.1 Nov 15, 2021
0.1.0 Oct 20, 2017

#415 in Algorithms

Download history 3920/week @ 2023-12-06 3523/week @ 2023-12-13 2880/week @ 2023-12-20 1782/week @ 2023-12-27 3795/week @ 2024-01-03 4106/week @ 2024-01-10 4207/week @ 2024-01-17 3631/week @ 2024-01-24 4408/week @ 2024-01-31 4120/week @ 2024-02-07 4334/week @ 2024-02-14 3866/week @ 2024-02-21 3793/week @ 2024-02-28 3180/week @ 2024-03-06 2821/week @ 2024-03-13 3280/week @ 2024-03-20

13,745 downloads per month
Used in 114 crates (10 directly)

Apache-2.0/MIT

43KB
440 lines

A quickselect algorithm adapted from Rust's implementation of the pdqsort algorithm.

NOTE: you may want to use Rust's official version of this algorithm, select_nth_unstable_by


lib.rs:

Pattern-defeating quickselect

The algorithm is based on pattern-defeating quicksort by Orson Peters, published at: https://github.com/orlp/pdqsort It is also heavily adapted from the Rust implementation of pdqsort (https://github.com/stjepang/pdqsort) and Rust's own slice::sort_unstable.

NOTE: you may want to use Rust's official version of this algorithm, slice::select_nth_unstable_by

Properties

  • Best-case running time is O(n).
  • Worst-case running time is O(n log n).
  • Does not allocate additional memory.
  • Uses #![no_std].

Examples

let mut v = [-5i32, 4, 1, -3, 2];
let k = 3;

pdqselect::select(&mut v, k);
let kth = v[k];
assert!(v[..k].iter().all(|&x| x <= kth));
assert!(v[k+1..].iter().all(|&x| x >= kth));

pdqselect::select_by(&mut v, k, |a, b| b.cmp(a));
let kth = v[k];
assert!(v[..k].iter().all(|&x| x >= kth));
assert!(v[k+1..].iter().all(|&x| x <= kth));

pdqselect::select_by_key(&mut v, k, |k| k.abs());
let kth = v[k].abs();
assert!(v[..k].iter().all(|&x| x.abs() <= kth));
assert!(v[k+1..].iter().all(|&x| x.abs() >= kth));

No runtime deps