# Cocktail Shaker Sort

Cocktail Shaker Sort – sorting in a shaker, a variant of bidirectional bubble sort.
The algorithm works like this:

1. Select the starting direction of the iteration in the loop (usually left-to-right)
2. Next, the numbers are checked in pairs
3. If the next element is larger, they are swapped
4. At the end, the iteration process restarts with the direction reversed
5. Iterates until there are no more permutations

The time complexity of the algorithm is similar to the bubble one – O(n2) .

An example implementation in PHP:

``````#!/usr/bin/env php
<?php

function cocktailShakeSort(\$numbers)
{
echo implode(",", \$numbers),"\n";
\$direction = false;
\$sorted = false;
do {
\$direction = !\$direction;
\$firstIndex = \$direction == true ? 0 : count(\$numbers) - 1;
\$lastIndex = \$direction == true ? count(\$numbers) - 1 : 0;

\$sorted = true;
for(
\$i = \$firstIndex;
\$direction == true ? \$i < \$lastIndex : \$i > \$lastIndex;
\$direction == true ? \$i++ : \$i--
) {
\$lhsIndex = \$direction ? \$i : \$i - 1;
\$rhsIndex = \$direction ? \$i + 1 : \$i;

\$lhs = \$numbers[\$lhsIndex];
\$rhs = \$numbers[\$rhsIndex];

if (\$lhs > \$rhs) {
\$numbers[\$lhsIndex] = \$rhs;
\$numbers[\$rhsIndex] = \$lhs;
\$sorted = false;
}
}
} while (\$sorted == false);

echo implode(",", \$numbers);
}

\$numbers = [2, 1, 4, 3, 69, 35, 55, 7, 7, 2, 6, 203, 9];
cocktailShakeSort(\$numbers);

?>``````