rust_dsa

Function select

Source
pub fn select<T>(slice: &[T], k: usize) -> &T
where T: Ord,
Expand description

Returns a reference to the kth smallest element in the slice.

This uses the quickselect algorithm.

§Panics

Panics if k is out of bounds.

§Example

use rust_dsa::select;

let nums = [80, 61, 36, 70, 53, 54, 59, 17, 76, 49];

assert_eq!(select(&nums, 4), &54);
assert_eq!(select(&nums, 6), &61);
assert_eq!(select(&nums, 0), &17);
assert_eq!(select(&nums, 9), &80);

let strs = ["foo", "bar", "baz"];

assert_eq!(select(&strs, 0), &"bar");
assert_eq!(select(&strs, 1), &"baz");
assert_eq!(select(&strs, 2), &"foo");