Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| BucketSort | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
6 | |
100.00% |
1 / 1 |
| sort | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
6 | |||
| 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 | * Bucketsort 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 BucketSort |
| 26 | { |
| 27 | /** |
| 28 | * Sort array |
| 29 | * |
| 30 | * @param array $list List of sortable elements |
| 31 | * @param int $bucketCount Buckets to divide the list into |
| 32 | * @param string $algo Algorithm to use for sort |
| 33 | * @param int $order Sort order |
| 34 | * |
| 35 | * @return array Sorted array |
| 36 | * |
| 37 | * @since 1.0.0 |
| 38 | */ |
| 39 | public static function sort(array $list, int $bucketCount, string $algo = InsertionSort::class, int $order = SortOrder::ASC) : array |
| 40 | { |
| 41 | $buckets = []; |
| 42 | $M = $list[0]::max($list); |
| 43 | |
| 44 | if ($bucketCount < 1) { |
| 45 | return []; |
| 46 | } |
| 47 | |
| 48 | if (\count($list) < 2) { |
| 49 | return $list; |
| 50 | } |
| 51 | |
| 52 | foreach ($list as $element) { |
| 53 | $buckets[(int) \floor(($bucketCount - 1) * $element->getValue() / $M)][] = $element; |
| 54 | } |
| 55 | |
| 56 | $sorted = []; |
| 57 | foreach ($buckets as $bucket) { |
| 58 | $sorted[] = $algo::sort($bucket, SortOrder::ASC); |
| 59 | } |
| 60 | |
| 61 | return $order === SortOrder::ASC ? \array_merge(...$sorted) : \array_reverse(\array_merge(...$sorted), false); |
| 62 | } |
| 63 | } |