Rust Program to Implement Selection Sort

Rust Program to Implement Selection Sort

Selection Sort is a fundamental sorting algorithm that helps beginners understand how to organize data step by step. Unlike Bubble Sort, which repeatedly swaps adjacent elements, Selection Sort finds the smallest element in the array and places it in its correct position. It then repeats this process for the remaining elements until the entire array is sorted. While not the fastest algorithm for large datasets, Selection Sort is simple, easy to understand, and a great way to learn the logic behind sorting.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

In Rust, implementing Selection Sort is an excellent exercise for learning about loops, arrays, and ownership. Since Rust emphasizes safety and performance, coding sorting algorithms like Selection Sort helps beginners understand how to manipulate data safely and efficiently. By practicing this algorithm, you can build a strong foundation for tackling more advanced sorting techniques later on.

Program 1: Selection Sort Using Loops

This first program demonstrates the classic Selection Sort using nested loops. It sorts a predefined array of integers.

fn selection_sort(arr: &mut [i32]) {

    let n = arr.len();

    for i in 0..n {

        let mut min_index = i;

        for j in i+1..n {

            if arr[j] < arr[min_index] {
                min_index = j;
            }

        }

        arr.swap(i, min_index);

    }

}

fn main() {

    let mut numbers = [29, 10, 14, 37, 13];

    println!("Original array: {:?}", numbers);

    selection_sort(&mut numbers);

    println!("Sorted array: {:?}", numbers);

}

This program works by finding the minimum element in the unsorted portion of the array and swapping it with the first unsorted element. Beginners can easily see how the smallest numbers gradually move to the front of the array.

Program 2: Selection Sort for Floating-Point Numbers

Selection Sort can also work with floating-point numbers. This example sorts decimals instead of integers.

fn selection_sort_floats(arr: &mut [f64]) {

    let n = arr.len();

    for i in 0..n {

        let mut min_index = i;

        for j in i+1..n {

            if arr[j] < arr[min_index] {
                min_index = j;
            }

        }

        arr.swap(i, min_index);

    }

}

fn main() {

    let mut numbers = [3.4, 1.2, 4.7, 0.5, 2.8];

    println!("Original array: {:?}", numbers);

    selection_sort_floats(&mut numbers);

    println!("Sorted array: {:?}", numbers);

}

This program helps beginners understand that the algorithm works with any type that supports comparisons. Rust’s type system ensures safety, and the swap operation moves the minimum element into place.

Program 3: Selection Sort Using Recursion

Selection Sort can also be implemented recursively, which is useful for understanding how recursion can replace loops.

fn selection_sort_recursive(arr: &mut [i32], start: usize) {

    if start >= arr.len() - 1 {
        return;
    }

    let mut min_index = start;

    for i in start+1..arr.len() {

        if arr[i] < arr[min_index] {
            min_index = i;
        }

    }

    arr.swap(start, min_index);
    selection_sort_recursive(arr, start + 1);

}

fn main() {

    let mut numbers = [64, 25, 12, 22, 11];

    println!("Original array: {:?}", numbers);

    selection_sort_recursive(&mut numbers, 0);

    println!("Sorted array: {:?}", numbers);

}

In this version, the function selects the minimum element, swaps it, and then calls itself on the remaining portion of the array. Beginners can learn how recursion divides problems into smaller tasks.

Program 4: Selection Sort with Characters

Selection Sort can sort non-numeric data such as characters. This example sorts a small array of letters.

fn selection_sort_chars(arr: &mut [char]) {

    let n = arr.len();

    for i in 0..n {

        let mut min_index = i;

        for j in i+1..n {

            if arr[j] < arr[min_index] {
                min_index = j;
            }

        }

        arr.swap(i, min_index);

    }

}

fn main() {

    let mut letters = ['d', 'a', 'c', 'b'];

    println!("Original array: {:?}", letters);

    selection_sort_chars(&mut letters);

    println!("Sorted array: {:?}", letters);

}

This program demonstrates that Selection Sort works for any comparable data type. Beginners see how the algorithm can handle different types without changing its core logic.

Program 5: Selection Sort Using Generics

Generics make Selection Sort reusable for multiple types in Rust. This program sorts both integers and characters.

fn selection_sort_generic<T: Ord>(arr: &mut [T]) {

    let n = arr.len();

    for i in 0..n {

        let mut min_index = i;

        for j in i+1..n {

            if arr[j] < arr[min_index] {
                min_index = j;
            }

        }

        arr.swap(i, min_index);

    }

}

fn main() {

    let mut int_arr = [20, 12, 35, 10, 5];
    let mut char_arr = ['x', 'b', 'm', 'a'];

    println!("Original integer array: {:?}", int_arr);
    selection_sort_generic(&mut int_arr);
    println!("Sorted integer array: {:?}", int_arr);

    println!("Original char array: {:?}", char_arr);
    selection_sort_generic(&mut char_arr);
    println!("Sorted char array: {:?}", char_arr);

}

Generics allow you to write a single function that works for multiple data types. Beginners can see how Rust makes code flexible and safe at the same time.

Frequently Asked Questions (FAQ)

This section clears up common doubts beginners often have about Selection Sort in Rust.

Q1: Why learn Selection Sort in Rust?
It helps beginners understand loops, comparisons, and swapping, while also practicing Rust’s safe data manipulation.

Q2: Is Selection Sort faster than Bubble Sort?
Selection Sort is usually slightly more efficient than Bubble Sort for small arrays, but both are not suitable for large datasets.

Q3: Can Selection Sort work with strings or characters?
Yes, as long as the type implements the Ord trait, Selection Sort can work with numbers, characters, or strings.

Q4: What is the main idea behind Selection Sort?
The algorithm repeatedly selects the smallest element from the unsorted portion and moves it to the sorted portion of the array.

Q5: When is Selection Sort most useful?
It is useful for small arrays or when learning sorting fundamentals before moving on to faster algorithms like Quick Sort or Merge Sort.

Conclusion

Selection Sort is a beginner-friendly algorithm that teaches how to organize data step by step. Implementing it in Rust reinforces understanding of loops, swaps, recursion, and generics. While it is not ideal for large datasets, mastering Selection Sort builds a strong foundation for learning advanced sorting algorithms and problem-solving in Rust. Practicing multiple versions—loops, recursion, floating-point, or generic types—helps beginners gain confidence and prepares them for more complex Rust programming tasks.

Scroll to Top