How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Rust programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Rust programming language
Table of Contents
Problem Statement
The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Rust programming language
Source code in the rust programming language
fn cocktail_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
loop {
let mut swapped = false;
let mut i = 0;
while i + 1 < len {
if a[i] > a[i + 1] {
a.swap(i, i + 1);
swapped = true;
}
i += 1;
}
if swapped {
swapped = false;
i = len - 1;
while i > 0 {
if a[i - 1] > a[i] {
a.swap(i - 1, i);
swapped = true;
}
i -= 1;
}
}
if !swapped {
break;
}
}
}
fn main() {
let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6];
println!("before: {:?}", v);
cocktail_sort(&mut v);
println!("after: {:?}", v);
}
You may also check:How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Lambdatalk programming language
You may also check:How to resolve the algorithm Averages/Arithmetic mean step by step in the Vim Script programming language
You may also check:How to resolve the algorithm Create an HTML table step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Galton box animation step by step in the Ruby programming language
You may also check:How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Isabelle programming language