w3resource

Rust Array Sorting Guide

Rust Arrays: Exercise-10 with Solution

Write a Rust program to create an array of integers with size 10 and initialize it with random values. Sort the array in ascending order and print the sorted array.

Sample Solution:

Rust Code:

use rand::Rng; // Import the rand crate to generate random numbers

fn main() {
    // Define an array with a size of 10 and initialize it with random values
    let mut arr: [i32; 10] = [0; 10]; // Declare an array of type i32 (integer) with a size of 10 and initialize it with zeros
    let mut rng = rand::thread_rng(); // Initialize the random number generator
    
    for i in 0..10 { // Iterate over each index of the array
        arr[i] = rng.gen_range(1..101); // Generate a random integer between 1 and 100 and assign it to the current index
    }

    // Sort the array in ascending order
    arr.sort(); // Use the sort method to sort the array in ascending order

    // Print the sorted array
    println!("Sorted Array: {:?}", arr); // Print the sorted array using debug formatting
}

Output:

Sorted Array: [1, 13, 16, 25, 31, 33, 58, 61, 72, 89]

Explanation:

Here is a brief explanation of the above Rust code:

  • use rand::Rng;: This line imports the rand::Rng trait from the "rand" crate, which provides functions for generating random numbers.
  • fn main() {: This line defines the main function, which is the entry point of the Rust program.
  • let mut arr: [i32; 10] = [0; 10];: This line declares an array named 'arr' of type 'i32' (integer) with a size of 10 and initializes it with zeros.
  • let mut rng = rand::thread_rng();: This line initializes the random number generator by creating a thread-local generator.
  • for i in 0..10 { ... }: This line starts a for loop that iterates over each index of the array arr.
  • arr[i] = rng.gen_range(1..101);: This line generates a random integer between 1 and 100 using the "gen_range()" method of the random number generator 'rng', and assigns it to the current index 'i' of the array 'arr'.
  • arr.sort();: This line sorts the array 'arr' in ascending order using the "sort()" method.
  • println!("Sorted Array: {:?}", arr);: This line prints the sorted array to the console using debug formatting.

Rust Code Editor:

Previous: Rust Array Concatenation Guide.
Next: Rust Vector Operations 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.