|
| 1 | +<?php |
| 2 | +declare(strict_types=1); |
| 3 | +/** |
| 4 | + * MIT License |
| 5 | + * |
| 6 | + * Copyright (c) 2018 Dogan Ucar |
| 7 | + * |
| 8 | + * @author Arthur Kurbidaev <[email protected]> |
| 9 | + * |
| 10 | + * Permission is hereby granted, free of charge, to any person obtaining a copy |
| 11 | + * of this software and associated documentation files (the "Software"), to deal |
| 12 | + * in the Software without restriction, including without limitation the rights |
| 13 | + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 14 | + * copies of the Software, and to permit persons to whom the Software is |
| 15 | + * furnished to do so, subject to the following conditions: |
| 16 | + * |
| 17 | + * The above copyright notice and this permission notice shall be included in all |
| 18 | + * copies or substantial portions of the Software. |
| 19 | + * |
| 20 | + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 21 | + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 22 | + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 23 | + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 24 | + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 25 | + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 26 | + * SOFTWARE. |
| 27 | + */ |
| 28 | + |
| 29 | +namespace doganoo\PHPAlgorithms\Algorithm\Sorting; |
| 30 | + |
| 31 | +use doganoo\PHPAlgorithms\Common\Interfaces\ISortable; |
| 32 | +use function array_fill; |
| 33 | +use function count; |
| 34 | +use function max; |
| 35 | + |
| 36 | +/** |
| 37 | + * Class BucketSort |
| 38 | + * |
| 39 | + * @package doganoo\PHPAlgorithms\Algorithm\Sorting |
| 40 | + */ |
| 41 | +class BucketSort implements ISortable { |
| 42 | + |
| 43 | + /** |
| 44 | + * @param array $array |
| 45 | + * @return array |
| 46 | + */ |
| 47 | + public function sort(array $array): array { |
| 48 | + if (empty($array)) { |
| 49 | + return []; |
| 50 | + } |
| 51 | + |
| 52 | + $size = count($array); |
| 53 | + $max = max($array); |
| 54 | + $buckets = array_fill(0, $size + 1, []); |
| 55 | + |
| 56 | + foreach ($array as $v) { |
| 57 | + $bucket = (int) ($size * $v / $max); |
| 58 | + $buckets[$bucket][] = $v; |
| 59 | + } |
| 60 | + |
| 61 | + $insertionSort = new InsertionSort(); |
| 62 | + for ($i = 0; $i < $size; ++$i) { |
| 63 | + $buckets[$i] = $insertionSort->sort($buckets[$i]); |
| 64 | + } |
| 65 | + |
| 66 | + $sorted = []; |
| 67 | + foreach ($buckets as $bucket) { |
| 68 | + foreach ($bucket as $v) { |
| 69 | + $sorted[] = $v; |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return $sorted; |
| 74 | + } |
| 75 | +} |
0 commit comments