Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
94.12% |
16 / 17 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| StoogeSort | |
94.12% |
16 / 17 |
|
50.00% |
1 / 2 |
7.01 | |
0.00% |
0 / 1 |
| __construct | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
| sort | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
2 | |||
| stooge | |
90.91% |
10 / 11 |
|
0.00% |
0 / 1 |
4.01 | |||
| 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 | * StoogeSort 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 StoogeSort 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 | $copy = $list; |
| 49 | self::stooge($copy, 0, $n - 1, $order); |
| 50 | |
| 51 | return $copy; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Recursively sort each 3rd of the list |
| 56 | * |
| 57 | * @param array $list Data to sort |
| 58 | * @param int $lo Lower bound |
| 59 | * @param int $hi Higher bound |
| 60 | * @param int $order Sort order |
| 61 | * |
| 62 | * @return void |
| 63 | * |
| 64 | * @since 1.0.0 |
| 65 | */ |
| 66 | private static function stooge(array &$list, int $lo, int $hi, int $order) : void |
| 67 | { |
| 68 | if ($lo >= $hi) { |
| 69 | return; |
| 70 | } |
| 71 | |
| 72 | if ($list[$lo]->compare($list[$hi], $order)) { |
| 73 | $temp = $list[$lo]; |
| 74 | $list[$lo] = $list[$hi]; |
| 75 | $list[$hi] = $temp; |
| 76 | } |
| 77 | |
| 78 | if ($hi - $lo + 1 > 2) { |
| 79 | $t = (int) (($hi - $lo + 1) / 3); |
| 80 | |
| 81 | self::stooge($list, $lo, $hi - $t, $order); |
| 82 | self::stooge($list, $lo + $t, $hi, $order); |
| 83 | self::stooge($list, $lo, $hi - $t, $order); |
| 84 | } |
| 85 | } |
| 86 | } |