Skip to content

Commit 37b43cd

Browse files
committed
PHP algorithm for Shaker Sort / Cocktail Sort with test
1 parent a96f29c commit 37b43cd

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

sort/shaker_sort/php/shaker_sort.php

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
<?php
2+
3+
function loop_replacing($start, $end, $items, $i) {
4+
// Replace elements
5+
$forward_is_lighter = $start < $end && $items[$start] > $items[$i];
6+
$backward_is_heavier = $start > $end && $items[$start] < $items[$i];
7+
8+
if ($forward_is_lighter || $backward_is_heavier) {
9+
$temp = $items[$start];
10+
$items[$start] = $items[$i];
11+
$items[$i] = $temp;
12+
unset($temp);
13+
}
14+
return $items;
15+
}
16+
17+
function shaker_sort($input) {
18+
$items = count($input) - 1;
19+
20+
$start = 0;
21+
$end = $items;
22+
while ($start !== $end) {
23+
if ($start < $end) {
24+
// Loop forward
25+
for ($i = $start; $i <= $end; $i++) {
26+
$input = loop_replacing($start, $end, $input, $i);
27+
}
28+
// Reduce next looping
29+
$start++;
30+
} else {
31+
// Loop backward
32+
for ($i = $start; $i >= $end; $i--) {
33+
$input = loop_replacing($start, $end, $input, $i);
34+
}
35+
// Reduce next looping
36+
$start--;
37+
}
38+
39+
// Switch start and end to revert moving through array
40+
$temp = $end;
41+
$end = $start;
42+
$start = $temp;
43+
unset($temp);
44+
45+
}
46+
47+
return $input;
48+
}
+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
3+
include "shaker_sort.php";
4+
5+
$array = [42, 5, 89, 2, 44, 0, 23, -2, 109, 76, 19, -6, 99, 98];
6+
$sorted = shaker_sort($array);
7+
8+
$expected = [-6, -2, 0, 2, 5, 19, 23, 42, 44, 76, 89, 98, 99, 109];
9+
echo ($expected == $sorted) ? 'Array is sorted !!' : 'Array is not sorted as expected';
10+
var_dump('array', $array, 'sorted set', $sorted);

0 commit comments

Comments
 (0)