Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
93.33% |
28 / 30 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
| CycleSort | |
93.33% |
28 / 30 |
|
0.00% |
0 / 1 |
15.07 | |
0.00% |
0 / 1 |
| __construct | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| sort | |
93.33% |
28 / 30 |
|
0.00% |
0 / 1 |
14.06 | |||
| 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 | * CycleSort 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 CycleSort 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 ($start = 0; $start < $n - 1; ++$start) { |
| 49 | $item = $list[$start]; |
| 50 | |
| 51 | $pos = $start; |
| 52 | $length0 = \count($list); |
| 53 | for ($i = $start + 1; $i < $length0; ++$i) { |
| 54 | if (!$list[$i]->compare($item, $order)) { |
| 55 | ++$pos; |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | if ($pos === $start) { |
| 60 | continue; |
| 61 | } |
| 62 | |
| 63 | while ($item->equals($list[$pos])) { |
| 64 | ++$pos; |
| 65 | } |
| 66 | |
| 67 | if ($pos !== $start) { |
| 68 | $old = $list[$pos]; |
| 69 | $list[$pos] = $item; |
| 70 | $item = $old; |
| 71 | } |
| 72 | |
| 73 | while ($pos !== $start) { |
| 74 | $pos = $start; |
| 75 | |
| 76 | for ($i = $start + 1; $i < $n; ++$i) { |
| 77 | if (!$list[$i]->compare($item, $order)) { |
| 78 | ++$pos; |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | while (isset($list[$pos]) && $item->equals($list[$pos])) { |
| 83 | ++$pos; |
| 84 | } |
| 85 | |
| 86 | if (isset($list[$pos])) { |
| 87 | $old = $list[$pos]; |
| 88 | $list[$pos] = $item; |
| 89 | $item = $old; |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | return $list; |
| 95 | } |
| 96 | } |