w3resource

Rust Vector sorting guide

Rust Vectors: Exercise-5 with Solution

Write a Rust program to create a vector with integers 5, 3, 9, 1, 7. Sort the vector in ascending order and print the sorted vector.

Sample Solution:

Rust Code:

// Define the main function, the entry point of the program
fn main() {
    // Create a vector with specified integers
    let mut numbers = vec![5, 3, 9, 1, 7];

    // Sort the vector in ascending order
    numbers.sort();

    // Print the sorted vector
    println!("Sorted vector: {:?}", numbers);
}

Output:

Sorted vector: [1, 3, 5, 7, 9]

Explanation:

Here is a brief explanation of the above Rust code:

  • fn main() {: Defines the main function, which is the entry point for a Rust program.
  • let mut numbers = vec![5, 3, 9, 1, 7];: Creates a mutable vector named 'numbers' and initializes it with the integers 5, 3, 9, 1, 7. The vector must be mutable so that it can be sorted.
  • numbers.sort();: Sorts the vector in-place in ascending order. The "sort()" method is available for vectors and it rearranges the elements of the vector so that they are in ascending order.
  • println!("Sorted vector: {:?}", numbers);: Prints the sorted vector to the console. The {:?} syntax is used for debug formatting, which is suitable for printing the contents of vectors.

Rust Code Editor:

Previous: Rust Vector iteration guide.
Next: Rust vector filtering guide.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.