Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
26 / 26 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
PancakeSort | |
100.00% |
26 / 26 |
|
100.00% |
1 / 1 |
9 | |
100.00% |
1 / 1 |
__construct | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
sort | |
100.00% |
26 / 26 |
|
100.00% |
1 / 1 |
8 |
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 | * PancakeSort 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 PancakeSort 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 | $n = \count($list); |
43 | |
44 | if ($n < 2) { |
45 | return $list; |
46 | } |
47 | |
48 | for ($i = $n; $i > 1; --$i) { |
49 | $m = 0; |
50 | for ($j = 0; $j < $i; ++$j) { |
51 | if ($list[$j]->compare($list[$m], $order)) { |
52 | $m = $j; |
53 | } |
54 | } |
55 | |
56 | if ($m !== $i - 1) { |
57 | // flip max/min to the beginning |
58 | $start = 0; |
59 | $c = $m; |
60 | |
61 | while ($start < $c) { |
62 | $temp = $list[$start]; |
63 | $list[$start] = $list[$c]; |
64 | $list[$c] = $temp; |
65 | |
66 | ++$start; |
67 | --$c; |
68 | } |
69 | |
70 | // flip reverse array |
71 | $start = 0; |
72 | $c = $i - 1; |
73 | |
74 | while ($start < $c) { |
75 | $temp = $list[$start]; |
76 | $list[$start] = $list[$c]; |
77 | $list[$c] = $temp; |
78 | |
79 | ++$start; |
80 | --$c; |
81 | } |
82 | } |
83 | } |
84 | |
85 | return $list; |
86 | } |
87 | } |