Rust program to sort an array in ascending order using bubble sort

Rust | Array Example: Write a program to sort an array in ascending order using bubble sort.
Submitted by Nidhi, on October 21, 2021

Problem Solution:

In this program, we will create an array of integer elements then we will sort the created array in ascending order using bubble sort.

Program/Source Code:

The source code to sort an array in ascending order using bubble sort is given below. The given program is compiled and executed successfully.

// Rust program to sort an array in 
// ascending order using bubble sort

fn main() 
{
    let mut arr:[usize;5] = [5,1,11,23,26];
    let mut i:usize=0;
    let mut j:usize=0;
    let mut t:usize=0;
    
    println!("Array before sorting: {:?}",arr);
    
    while i<5
    {
        j=0;
        while j<(5-i-1)
        {
            if arr[j] > arr[j+1] 
            {
            	t      = arr[j];
            	arr[j] = arr[j+1];
            	arr[j+1] = t;
            }
            j=j+1;
        }
        i=i+1;
    }	
    println!("Array after sorting: {:?}",arr);
}

Output:

Array before sorting: [5, 1, 11, 23, 26]
Array after sorting: [1, 5, 11, 23, 26]

Explanation:

Here, we created an array of the integer with 5 elements and then we sorted the created array in ascending order using bubble sort. After that, we printed the sorted array.

Rust Arrays Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.