forked from TheAlgorithms/PHP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RadixSort.php
92 lines (78 loc) · 1.32 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
/**
* Radix Sort
*
* @param array $arr
* @return array
*/
function radixSort($nums)
{
$maxDigitsCount = maxDigits($nums);
for ($k=0; $k < $maxDigitsCount; $k++)
{
$digitBucket = array_fill(0,10,[]);
for ($i=0; $i < count($nums); $i++)
{
$digitBucket[getDigit($nums[$i], $k)][] = $nums[$i];
}
$nums = concat($digitBucket);
}
return $nums;
}
/*
* Helper functions
*/
/**
* Get the digits value by it's place
*
* @param $num
* @param $k
* @return int
*/
function getDigit($num, $i)
{
return floor(abs($num) / pow(10, $i)) % 10;
}
/**
* Get the digits count
*
* @param $nums
* @return int
*/
function digitsCount($num)
{
if ($num == 0) return 1;
return floor(log10(abs($num))) + 1;
}
/**
* Get the max digits count
*
* @param $nums
* @return int
*/
function maxDigits($arr)
{
$maxDigits = 0;
for ($i=0; $i < count($arr); $i++)
{
$maxDigits = max($maxDigits, digitsCount($arr[$i]));
}
return $maxDigits;
}
/**
* Concat the array
*
* @param $arr
* @return array
*/
function concat(array $array) {
$newArray=[];
for ($i = 0; $i < count($array); $i++)
{
for ($j = 0; $j<count($array[$i]); $j++)
{
$newArray[] = $array[$i][$j];
}
}
return $newArray;
}