Sure, here is a Rust function to find the median of a list of numbers:
Rust
fn find_median(numbers: &[i32]) -> Option<i32> {
let mut sorted_numbers = numbers.to_vec();
sorted_numbers.sort();
if sorted_numbers.len() % 2 == 0 {
// The list has an even number of elements, so the median is the average of the two middle elements.
let middle_index = sorted_numbers.len() / 2;
return Some((sorted_numbers[middle_index - 1] + sorted_numbers[middle_index]) / 2);
} else {
// The list has an odd number of elements, so the median is the middle element.
let middle_index = sorted_numbers.len() / 2;
return Some(sorted_numbers[middle_index]);
}
}
fn main() {
let numbers = [1, 3, 2, 5, 4];
let median = find_median(&numbers);
println!("The median is {}", median);
}
This function first defines a function called find_median that takes a vector of i32 numbers as input and returns the median of the list. The function first sorts the vector of numbers. Then, it checks if the number of elements in the vector is even or odd. If the number of elements is even, then the median is the average of the two middle elements. If the number of elements is odd, then the median is the middle element.
The main function of the program then calls the find_median function with the vector [1, 3, 2, 5, 4] as input. The result of the function call is then printed to the console.
To run the program, you can save it as a file called find_median.rs and then compile it using the following command:
Code snippet
rustc find_median.rs
Once the program is compiled, you can run it using the following command:
Code snippet
./find_median
This will print the following output to the console:
Code snippet
The median is 3
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Sure, here is a Rust function to find the median of a list of numbers:
Rust
This function first defines a function called
find_medianthat takes a vector of i32 numbers as input and returns the median of the list. The function first sorts the vector of numbers. Then, it checks if the number of elements in the vector is even or odd. If the number of elements is even, then the median is the average of the two middle elements. If the number of elements is odd, then the median is the middle element.The main function of the program then calls the
find_medianfunction with the vector [1, 3, 2, 5, 4] as input. The result of the function call is then printed to the console.To run the program, you can save it as a file called
find_median.rsand then compile it using the following command:Code snippet
Once the program is compiled, you can run it using the following command:
Code snippet
This will print the following output to the console:
Code snippet