Home >Backend Development >PHP Tutorial >Detailed explanation of PHP bubble algorithm (recursive implementation), bubble recursion_PHP tutorial
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));
Result:
Question:
I encountered a problem when trying this implementation, which has not yet been solved.
Here:
/******************
If you use the third line directly instead of $index++ first, and then ruturn, you will enter an infinite loop. I output $index at the beginning of the function, both are 0, which means that the parameters passed to the recursive function after $index++ are not $index++ as they should be. The result (i.e. $index=$index+1).
Isn’t maoPao($array, $index++) a short way to write $index++; return maoPao($array, $index);? Why are the two results different? I hope you can get your answers.
******************/
Supplement:
Answer:
$index = 1;
$m = $index++;
echo $index.'
'; //The result is 2
echo $m.'
'; //The result is 1. Because it is a post-increment, the initial $index=1 will be assigned to $m first, and then $index will increase by 1;
$index = 1;
$n = ++$index;
echo $index.'
'; //The result is 2
echo $n; //The result is 2. Because it is a pre-increment, the operation of $index+1 will be performed first, and then assigned to $n;
This may not be easy to remember, so you must pay attention when using it. In the above question, I just ignored this problem, which caused $index to infinitely pass the value of 0 and cause the recursion to lock.