-
Notifications
You must be signed in to change notification settings - Fork 0
/
RadixSort.php
50 lines (39 loc) · 1.3 KB
/
RadixSort.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php
namespace CS\Sort;
use CS\Interfaces\SortInterface;
use CS\Traits\SortTrait;
class RadixSort implements SortInterface
{
use SortTrait;
/**
* @inheritDoc
*/
public function sort(array $input): array
{
// Clean the array.
$input = $this->cleanTheArrayData($input);
// Find the Longest Digit based on the values of the array.
$longest = max(array_map('strlen', $input));
// Make an array of 10 empty arrays.
$buckets = array_fill(0, 10, []);
for ($i = $longest - 1; $i >= 0; $i--) {
while (isset($input) && $input) {
$current = array_shift($input);
$digit = $this->getMaximumNumberOfDigit($current, $i, $longest);
$buckets[$digit][] = $current;
}
for ($j = 0; $j < 10; $j++) {
while (isset($buckets[$j]) && $buckets[$j]) {
$input[] = array_shift($buckets[$j]);
}
}
}
return $input;
}
protected function getMaximumNumberOfDigit(int $number, int $place, int $longestNumber): int
{
$numberToArray = str_split((string) $number);
$mod = $longestNumber - count($numberToArray);
return (int) ($numberToArray[$place - $mod] ?? '0');
}
}