How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Sidef programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Sidef 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 Sidef programming language
Source code in the sidef programming language
func cocktailsort(a) {
var swapped = false
func cmpsw(i) {
if (a[i] > a[i+1]) {
a[i, i+1] = a[i+1, i]
swapped = true
}
}
var max = a.end
do {
{|i| cmpsw(i) } << ^max
swapped.not! && break
{|i| cmpsw(max-i) } << 1..max
} while (swapped)
return a
}
var numbers = [7,6,5,9,8,4,3,1,2,0]
say cocktailsort(numbers)
var strs = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]
say cocktailsort(strs)
You may also check:How to resolve the algorithm Menu step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Hello world/Text step by step in the Brainf*** programming language
You may also check:How to resolve the algorithm Solve a Holy Knight's tour step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Mind boggling card trick step by step in the Crystal programming language