PHP Implementation cardinality sorting
Just started to learn the algorithm, hit the base sort, just try to achieve with PHP, but there is no place to understand
Where the red font is, why do we have to do it correctly?
I hope someone can help me to see if this is right, or who can put a beautiful point of writing (PHP) to give me a reference,
Appreciate
/*
* Count Sort
* $a is an array that stores a number of digits
* $arr is the array to be sorted
*/
function Countsort ($a, $arr) {
$b = Array ();
foreach ($a as $value) {
$b [$value]++;
}
for ($i = 1; $i < count ($b); $i + +) {
$b [$i] = $b [$i] + $b [$i-1];
}
$c = Array ();
for ($i = count ($a)-1; $i >= 0; $i-) {
$c [$b [$a [$i]] = $arr [$i];
$b [$a [$i]] = $b [$a [$i]]-1;
}
return $c;
}
/*
* Gets a numeric value for each number in the array and returns the array
* $num, used to get the array of digits
* $tail which digits to get
*/
function GetTail ($num, $tail) {
for ($i = 0; $i < count ($num); $i + +) {
if ($num [$i] < POW (ten, $tail)) {
if ($num [$i] >= Pow (Ten, $tail-1)) {
$temp [$i]=floor ($num [$i]/pow ($tail-1));
}else{
$temp [$i] = floor (0);
}
}else{
$temp [$i] = Floor ($num [$i]%pow ($tail)/POW (Ten, $tail-1));
$flag = true;
}
}
return $temp;
}
/*
* Base Sort
*/
function Basesort ($arr) {
4 represents the number of the largest number in the array to be sorted
For ($i = 1; $i <=4; $i + +) {
$temp = GetTail ($arr, $i);
$arr = Countsort ($temp, $arr);
for ($j = 1; $j <= count ($arr); $j + +) {
$new [$j-1] = $arr [$j];
}
$arr = $new;
}
return $arr;
}
$arr = Array (11,342,543,213,98,312,0,234,322,455,164,88,100,999,1000);
Print_r (Basesort ($arr));
?>
------Solution--------------------
This post was last edited by xuzuning on 2014-03-02 11:56:47
I can not see your ideas, according to the principle of the basis of the order to write
$a = array (11,342,543,213,98,312,0,234,322,455,164,88,100,999,1000);
$t = Radix_sort ($a);
echo Join (', ', $t);
function Radix_sort ($ar, $p =1) {
$m = 0;
foreach ($ar as $v) {
$m = Max ($m, strlen ($v));
$k = strlen ($v) >= $p? SUBSTR ($v,-$p, 1): 0;
$t [$k] = $v;
}
$res = Array ();
for ($i =0; $i <10; $i + +) {
if (Isset ($t [$i])) foreach ($t [$i] as $v) $res [] = $v;
}
return $m > $p? Radix_sort ($res, $p + 1): $res;
}
0,11,88,98,100,164,213,234,312,322,342,455,543,999,1000