I am learning Rust and I would like to get some feedback around my solution to calculate the median value from a list of integers.
I believe the logic is correct as my tests pass, but I'm concerned the right types and if I coded "the Rust way".
use std::f32;
fn main() {
let mut v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
v.push(9);
println!("{:?}", get_median(v)); // 7
v = Vec::new();
v.push(5);
v.push(6);
v.push(7);
v.push(8);
v.push(9);
v.push(10);
println!("{:?}", get_median(v)); // 7.5
v = Vec::new();
v.push(6);
v.push(5);
v.push(10);
v.push(7);
v.push(9);
v.push(8);
println!("{:?}", get_median(v)); // 7.5
v = Vec::new();
v.push(-2);
v.push(-9);
v.push(-4);
v.push(-1);
v.push(0);
v.push(6);
println!("{:?}", get_median(v)); // -1.5
}
fn get_median(numbers: Vec<i32>) -> f32 {
let mut v = numbers;
v.sort();
let length = v.len() as f32;
if length%2.0 == 1.0 {
let index = length as usize / 2;
v[index] as f32
} else {
let index = length as usize / 2;
let lower_mid: usize = index - 1;
let higher_mid: usize = index;
(v[lower_mid] + v[higher_mid]) as f32 / 2.0
}
}