Realize
Copy Code code as follows:
/*
Bubble algorithm (Recursive implementation)
*/
function Maopao ($array, $index =0)
{
$count = count ($array);
if (($count-1) <= $index)
return $array;
for ($i = $count-1; $i > $index; $i-)
{
if ($array [$i] < $array [$i-1])
{
$tmp = $array [$i];
$array [$i] = $array [$i-1];
$array [$i-1] = $tmp;
}
}
$index + +;
Return Maopao ($array, $index);
Return Maopao ($array, $index + +);
}
$arr = Array (12,4,3,1,9,5,6,8,7);
Var_dump (Maopao ($arr));
Results:
Copy Code code as follows:
Array ([0] => 1 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 [7] => 9 [8] => 12)
Problem:
A problem has been encountered in attempting this implementation and has not been resolved.
Over here:
Copy Code code as follows:
$index + +;
Return Maopao ($array, $index);
Return Maopao ($array, $index + +);
/******************
If you use the third line directly, instead of first $index++, then the Ruturn will go into the dead loop. I output $index at the beginning of the function, which means that the parameters passed to the recursive function after $index++ are not the result of $index++ (that is, $index=$ index+1).
Maopao ($array, $index + +) is not $index++; Return Maopao ($array, $index); the short writing, why the two results are not the same, I hope you can answer.
******************/
Add:
Answer:
Copy Code code as follows:
$index + + $index The difference between the two, $index + + is called the post increment, + + $index is called the forward increment, although the final $index results are +1. But there are different places to pass variables.
$index = 1;
$m = $index + +;
echo $index. ' <br/> '; Result is 2
echo $m. ' <br/> '; The result is 1. Since it is the post increment, the initial $index=1 will be assigned to $m, then the $index is increased by 1;
$index = 1;
$n = + + $index;
echo $index. ' <br/> '; Result is 2
Echo $n; The result is 2. Because it is the front increment, it will perform the $index+1 operation first, then assign the value to $n;
This may not be very good remember, so in the use of the time must pay attention to, in the above problem I just ignore this problem caused by the $index infinite Pass 0 value makes recursive lock dead.