rust_dsa

Function select_in_place

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

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

The elements in the slice may get rearanged according to the quickselect algorithm.

§Panics

Panics if k is out of bounds.

§Example

use rust_dsa::select_in_place;

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

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

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

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