OneBite.Dev - Coding blog in a bite size

Sort Items In Array By Desc In Rust

Code snippet for how to Sort Items In Array By Desc In Rust with sample and detail explanation

Rust is a powerful systems programming language that places a high value on speed, security, and concurrency. This article will guide you through the process of sorting array items in descending order in Rust.

Code Snippet: Sorting Array Items in Descending Order

fn main() {
    let mut array = [5, 2, 1, 3, 4];
    array.sort_by(|a, b| b.cmp(a));
    println!("{:?}", array);
}

Code Explanation: Sorting Array Items in Descending Order

In our main function, we declare a mutable array with five integers. We then sort the array in descending order using the sort_by method.

Here’s a step by step breakdown:

  1. Declare the main function with fn main(). This is the function that will be first executed in any standalone Rust program.

  2. Inside the main function we declare a mutable array: let mut array = [5, 2, 1, 3, 4];. The keyword mut allows us to change the contents of the array. Without it, the array would be immutable and we wouldn’t be able to sort it.

  3. Next, we use the sort_by method: array.sort_by(|a, b| b.cmp(a));. The parameters a and b are references to the elements inside the array. The cmp function compares the two parameters and sorts them in ascending order by default. However, because we’ve reversed the parameters ‘a’ and ‘b’ in our closure, the comparison results in a descending order sort.

  4. The println!("{:?}", array); statement prints the sorted array to the console. The {:?} placeholder tells Rust to use the “Debug” formatter, which can print out most types.

  5. Finally, run the program. Your console should output: [5, 4, 3, 2, 1]

This is a brief introduction to sorting arrays in Rust, which can be useful in several different algorithm and data manipulation scenarios.

rust