Skip to content

Commit bfa49cd

Browse files
Merge pull request kennyledet#491 from jakobhans/cocktailsort-php
PHP implementation of Cocktail Sort
2 parents 28e2c21 + 289c283 commit bfa49cd

2 files changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
// Cocktail Sort (AKA Bidirectional Bubble Sort / Cocktail Shaker Sort / Shaker Sort) - https://en.wikipedia.org/wiki/Cocktail_sort
4+
5+
function cocktailSort($array)
6+
{
7+
$toggled = FALSE;
8+
do {
9+
for ($i = 0; $i < count($array) - 2; $i++) {
10+
if ($array[$i] > $array[$i+1]) {
11+
$temp = $array[$i];
12+
$array[$i] = $array[$i+1];
13+
$array[$i+1] = $temp;
14+
$toggled = TRUE;
15+
}
16+
}
17+
18+
if (!$toggled) {
19+
break;
20+
}
21+
22+
$toggled = FALSE;
23+
24+
for ($i = count($array) - 2; $i > 0; $i--) {
25+
if ($array[$i] > $array[$i+1]) {
26+
$temp = $array[$i];
27+
$array[$i] = $array[$i+1];
28+
$array[$i+1] = $temp;
29+
$toggled = TRUE;
30+
}
31+
}
32+
} while ($toggled);
33+
34+
return $array;
35+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
require('Cocktailsort.php');
4+
5+
class CocktailsortTest extends PHPUnit_Framework_TestCase {
6+
private $test_array = array(88, 4, 7, 85, 45, 3, 1, 66, 24, 59, 2);
7+
8+
public function testCocktailsort()
9+
{
10+
$result = cocktailSort($this->test_array);
11+
sort($this->test_array, SORT_NUMERIC);
12+
13+
$this->assertEquals($result, $this->test_array);
14+
}
15+
}

0 commit comments

Comments
 (0)