find the median of a list of numbers in rust

To find the median of a list of numbers in Rust, we can start by sorting the list using the sort() method provided by Rust's Vec data structure. Once the list is sorted, we can then find the middle element or elements, which will give us the median.

Here's one way to find the median of a list of numbers in Rust:

main.rs
fn find_median(list: &mut Vec<i32>) -> f32 {
    list.sort();

    let middle = list.len() / 2;

    if list.len() % 2 == 0 {
        // if the list has an even number of elements, we need to average the middle two values
        let median_sum = (list[middle - 1] + list[middle]) as f32;
        median_sum / 2.0
    } else {
        // if the list has an odd number of elements, the middle element is the median
        list[middle] as f32
    }
}

fn main() {
    let mut list = vec![4, 2, 5, 3, 1];
    let median = find_median(&mut list);
    println!("Median: {}", median);
}
582 chars
21 lines

In the above code, we define a find_median() function that takes in a mutable reference to a Vec of i32 values. We then call the sort() method on the list to sort it in ascending order.

Next, we calculate the index of the middle element. If the list has an even number of elements, we calculate the average of the middle two values. If the list has an odd number of elements, we simply return the middle element.

In the main() function, we create a Vec of numbers, call find_median() on it, and print the resulting median to the console.

gistlibby LogSnag