How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the Rust programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the Rust programming language

Table of Contents

Problem Statement

Sort an array of integers (of any convenient size) into ascending order using Pancake sorting. In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so: Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.) Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations are optional (but recommended).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting algorithms/Pancake sort step by step in the Rust programming language

Source code in the rust programming language

fn pancake_sort<T: Ord>(v: &mut [T]) {
    let len = v.len();
    // trivial case -- no flips
    if len < 2 {
        return;
    }
    for i in (0..len).rev() {
        // find index of the maximum element within `v[0..i]` (inclusive)
        let max_index = v.iter()
            .take(i + 1)
            .enumerate()
            .max_by_key(|&(_, elem)| elem)
            .map(|(idx, _)| idx)
            // safe because we already checked if `v` is empty
            .unwrap();
        // if `max_index` is not where it's supposed to be
        // do two flips to move it to `i`
        if max_index != i {
            flip(v, max_index);
            flip(v, i);
        }
    }
}

// function to flip a section of a mutable collection from 0..num (inclusive)
fn flip<E: PartialOrd>(v: &mut [E], num: usize) {
    v[0..num + 1].reverse();
}

fn main() {
    // Sort numbers
    let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1];
    println!("Before: {:?}", numbers);
    pancake_sort(&mut numbers);
    println!("After: {:?}", numbers);

    // Sort strings
    let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"];
    println!("Before: {:?}", strings);
    pancake_sort(&mut strings);
    println!("After: {:?}", strings);
}


  

You may also check:How to resolve the algorithm Multiple regression step by step in the Stata programming language
You may also check:How to resolve the algorithm Count in octal step by step in the Frink programming language
You may also check:How to resolve the algorithm Semordnilap step by step in the Ksh programming language
You may also check:How to resolve the algorithm Yin and yang step by step in the C++ programming language
You may also check:How to resolve the algorithm Sorting algorithms/Quicksort step by step in the VBA programming language