cocktail sort


See On Github

Data

Contributor

Generic placeholder thumbnail

by jakobhans

in php

Source Code

<?php

// Cocktail Sort (AKA Bidirectional Bubble Sort / Cocktail Shaker Sort / Shaker Sort) - https://en.wikipedia.org/wiki/Cocktail_sort

function cocktailSort($array)
{
    $toggled = FALSE;
    do {
        for ($i = 0; $i < count($array) - 2; $i++) {
            if ($array[$i] > $array[$i+1]) {
                $temp = $array[$i];
                $array[$i] = $array[$i+1];
                $array[$i+1] = $temp;
                $toggled = TRUE;
            }
        }

        if (!$toggled) {
            break;
        }

        $toggled = FALSE;

        for ($i = count($array) - 2; $i > 0; $i--) {
            if ($array[$i] > $array[$i+1]) {
                $temp = $array[$i];
                $array[$i] = $array[$i+1];
                $array[$i+1] = $temp;
                $toggled = TRUE;
            }
        }
    } while ($toggled);

    return $array;
}
<?php

require('Cocktailsort.php');

class CocktailsortTest extends PHPUnit_Framework_TestCase {
    private $test_array = array(88, 4, 7, 85, 45, 3, 1, 66, 24, 59, 2);

    public function testCocktailsort()
    {
        $result = cocktailSort($this->test_array);
        sort($this->test_array, SORT_NUMERIC);

        $this->assertEquals($result, $this->test_array);
    }
}