How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Haxe programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Cocktail sort step by step in the Haxe 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 Haxe programming language
Source code in the haxe programming language
class CocktailSort {
public static function sort<T>(arr:Array<T>) {
var swapped = false;
do {
swapped = false;
for (i in 0...(arr.length - 1)) {
if (Reflect.compare(arr[i], arr[i + 1]) > 0) {
var temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
if (!swapped) break;
swapped = false;
var i = arr.length - 2;
while (i >= 0) {
if (Reflect.compare(arr[i], arr[i + 1]) > 0) {
var temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
i--;
}
} while (swapped);
}
}
class Main {
static function main() {
var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0];
var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3,
3.5, 0.0, -4.1, -9.5];
var stringArray = ['We', 'hold', 'these', 'truths', 'to',
'be', 'self-evident', 'that', 'all',
'men', 'are', 'created', 'equal'];
Sys.println('Unsorted Integers: ' + integerArray);
CocktailSort.sort(integerArray);
Sys.println('Sorted Integers: ' + integerArray);
Sys.println('Unsorted Floats: ' + floatArray);
CocktailSort.sort(floatArray);
Sys.println('Sorted Floats: ' + floatArray);
Sys.println('Unsorted Strings: ' + stringArray);
CocktailSort.sort(stringArray);
Sys.println('Sorted Strings: ' + stringArray);
}
}
You may also check:How to resolve the algorithm Pick random element step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Tic-tac-toe step by step in the Tailspin programming language
You may also check:How to resolve the algorithm Thiele's interpolation formula step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Thue-Morse step by step in the Perl programming language
You may also check:How to resolve the algorithm Terminal control/Coloured text step by step in the BBC BASIC programming language