Bubble Sort Algorithm in Rust

1. Introduction

The Bubble Sort algorithm is one of the simplest sorting algorithms. It works by repeatedly stepping through the list, comparing adjacent items, and swapping them if they are in the wrong order. The process is repeated until no more swaps are needed, indicating that the list is sorted.

2. Implementation Steps

1. Start from the first element and compare it with the next element.

2. If the current element is greater than the next element, then swap them.

3. Continue the process for each element in the list until the entire array is sorted.

4. After each pass through the array, the largest unsorted value will have "bubbled up" to its correct position.

5. Reduce the size of the unsorted section of the array by one and repeat the process.

3. Implementation in Rust Programming

fn bubble_sort<T: Ord>(arr: &mut [T]) {
    let mut n = arr.len();
    let mut swapped;
    while n != 0 {
        swapped = 0;
        for i in 1..n {
            // If the adjacent elements are in wrong order, swap them
            if arr[i - 1] > arr[i] {
                arr.swap(i - 1, i);
                swapped = i;
            }
        }
        n = swapped;
    }
}
fn main() {
    let mut numbers = [8, 2, 4, 9, 3, 6];
    bubble_sort(&mut numbers);
    println!("{:?}", numbers); // Prints: [2, 3, 4, 6, 8, 9]
}

Output:

[2, 3, 4, 6, 8, 9]

Explanation:

1. We define the bubble_sort function which works on slices of data that can be ordered (Ord).

2. We set n to be the length of the array. This will help us reduce the unsorted part of the array in each iteration.

3. The swapped variable keeps track of the last swap position in the array. If no swaps are made during a pass, it means the array is sorted.

4. The inner loop iterates through the unsorted section of the array, comparing each element with the next. If they are out of order, they are swapped.

5. The process is repeated until no swaps are needed.


Comments