---
title: "Create a function to find the median of a list of numbers using Rust."  
description: "Create a function to find the median of a list of numbers using Rust."  
author: "Utpal Vishwas"  
published: 2023-06-22  
updated: 2023-06-23  
canonical: https://www.mindstick.com/forum/158837/create-a-function-to-find-the-median-of-a-list-of-numbers-using-rust  
category: "rust"  
tags: ["programs", "rust"]  
reading_time: 2 minutes  

---

# Create a function to find the median of a list of numbers using Rust.

Create a [function](https://www.mindstick.com/articles/13001/multi-statement-table-valued-user-defined-function-in-sql-server) to find the median of a list of numbers using Rust.

## Replies

### Reply by Aryan Kumar

Sure, here is a Rust function to find the median of a list of numbers:

Rust

```plaintext
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

```plaintext
rustc find_median.rs
```

Once the program is compiled, you can run it using the following command:

Code snippet

```plaintext
./find_median
```

This will print the following output to the console:

Code snippet

```plaintext
The median is 3
```


---

Original Source: https://www.mindstick.com/forum/158837/create-a-function-to-find-the-median-of-a-list-of-numbers-using-rust

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
