Function sort3

Source
pub fn sort3<'a, T: PartialOrd + Copy>(
    a: &'a T,
    b: &'a T,
    c: &'a T,
) -> (&'a T, &'a T, &'a T)
Expand description

Sorts a set of three values in increasing order.

This function efficiently sorts three values using a minimal number of comparisons (between 2 and 3 comparisons). The values are passed by reference and references are returned, making this efficient for larger types.

§Arguments

  • a - Reference to the first value
  • b - Reference to the second value
  • c - Reference to the third value

§Returns

A tuple of three references (&min, &mid, &max) in sorted order.

§Examples

§Basic Sorting

use parry3d::utils::sort3;

let x = 5.0;
let y = 2.0;
let z = 8.0;

let (min, mid, max) = sort3(&x, &y, &z);

assert_eq!(*min, 2.0);
assert_eq!(*mid, 5.0);
assert_eq!(*max, 8.0);

§All Permutations Work

use parry3d::utils::sort3;

let a = 1.0;
let b = 2.0;
let c = 3.0;

// All orderings produce the same sorted result
let (min1, mid1, max1) = sort3(&a, &b, &c);
let (min2, mid2, max2) = sort3(&c, &a, &b);
let (min3, mid3, max3) = sort3(&b, &c, &a);

assert_eq!(*min1, *min2);
assert_eq!(*min1, *min3);
assert_eq!(*max1, *max2);
assert_eq!(*max1, *max3);

§Finding Median of Three

use parry3d::utils::sort3;

let values = [10.0, 5.0, 7.0];
let (_, median, _) = sort3(&values[0], &values[1], &values[2]);

// The middle value is the median
assert_eq!(*median, 7.0);

§Works with Integers

use parry3d::utils::sort3;

let x = 42;
let y = 17;
let z = 99;

let (min, mid, max) = sort3(&x, &y, &z);

assert_eq!(*min, 17);
assert_eq!(*mid, 42);
assert_eq!(*max, 99);