make-github-pseudonymous-again / js-sorting

:signal_strength: Sorting algorithms for JavaScript
https://make-github-pseudonymous-again.github.io/js-sorting
GNU Affero General Public License v3.0
3 stars 0 forks source link

Cocktail sort #42

Open make-github-pseudonymous-again opened 9 years ago

make-github-pseudonymous-again commented 9 years ago

https://en.wikipedia.org/wiki/Cocktail_sort

make-github-pseudonymous-again commented 9 years ago

Example in PHP

function cocktailSort(&$a) {
    $n = count($a);
    $left = 0;
    $right = $n - 1;
    do {
        //echo "# Left: ".$left." Right: ".$right.EOL;
        for ($i = $left; $i < $right; $i++) {
            //echo "Comparation: ";
            //printArray($a, array($i, $i + 1));
            if ($a[$i] > $a[$i + 1]) {
                //echo "Swap ";
                list($a[$i], $a[$i + 1]) = array($a[$i + 1], $a[$i]);
                //printArray($a, array($i, $i + 1), 'blue');
            }
        }
        $right -= 1;
        for ($i = $right; $i > $left; $i--) {
            //echo "Comparation: ";
            //printArray($a, array($i, $i - 1));
            if ($a[$i] < $a[$i - 1]) {
                //echo "Swap ";
                list($a[$i], $a[$i - 1]) = array($a[$i - 1], $a[$i]);
                //printArray($a, array($i, $i - 1), 'blue');
            }
        }
        $left += 1;
    } while ($left <= $right);
}