Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
CocktailShakerSort | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
8 | |
100.00% |
1 / 1 |
__construct | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
sort | |
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |
7 |
1 | <?php |
2 | /** |
3 | * Jingga |
4 | * |
5 | * PHP Version 8.1 |
6 | * |
7 | * @package phpOMS\Algorithm\Sort; |
8 | * @copyright Dennis Eichhorn |
9 | * @license OMS License 2.0 |
10 | * @version 1.0.0 |
11 | * @link https://jingga.app |
12 | */ |
13 | declare(strict_types=1); |
14 | |
15 | namespace phpOMS\Algorithm\Sort; |
16 | |
17 | /** |
18 | * CocktailShakerSort class. |
19 | * |
20 | * @package phpOMS\Algorithm\Sort; |
21 | * @license OMS License 2.0 |
22 | * @link https://jingga.app |
23 | * @since 1.0.0 |
24 | */ |
25 | final class CocktailShakerSort implements SortInterface |
26 | { |
27 | /** |
28 | * Constructor |
29 | * |
30 | * @since 1.0.0 |
31 | * @codeCoverageIgnore |
32 | */ |
33 | private function __construct() |
34 | { |
35 | } |
36 | |
37 | /** |
38 | * {@inheritdoc} |
39 | */ |
40 | public static function sort(array $list, int $order = SortOrder::ASC) : array |
41 | { |
42 | $start = 0; |
43 | $end = \count($list) - 1; |
44 | |
45 | if ($end < 1) { |
46 | return $list; |
47 | } |
48 | |
49 | while ($start <= $end) { |
50 | $newStart = $end; |
51 | $newEnd = $start; |
52 | |
53 | for ($i = $start; $i < $end; ++$i) { |
54 | if ($list[$i]->compare($list[$i + 1], $order)) { |
55 | $old = $list[$i]; |
56 | $list[$i] = $list[$i + 1]; |
57 | $list[$i + 1] = $old; |
58 | |
59 | $newEnd = $i; |
60 | } |
61 | } |
62 | |
63 | $end = $newEnd - 1; |
64 | |
65 | for ($i = $end; $i >= $start; --$i) { |
66 | if ($list[$i]->compare($list[$i + 1], $order)) { |
67 | $old = $list[$i]; |
68 | $list[$i] = $list[$i + 1]; |
69 | $list[$i + 1] = $old; |
70 | |
71 | $newStart = $i; |
72 | } |
73 | } |
74 | |
75 | $start = $newStart + 1; |
76 | } |
77 | |
78 | return $list; |
79 | } |
80 | } |