accomplish
/*
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));
result:
Array ( [0] => 1 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 [7] => 9 [8] => 12 )
question:
I encountered a problem when trying this implementation, which has not been resolved yet.
Here:
$index++;
return maoPao($array, $index);
//return maoPao($array, $index++);
/******************
If you use the third line directly instead of $index++ first and then ruturn, you will enter a dead loop. I output $index at the beginning of the function, which is 0, which means that the parameters passed to the recursive function after $index++ are not the result of $index++ (that is, $index=$index+1).
Is maoPao($array, $index++) not a short writing method of $index++; return maoPao($array, $index);? Why are the two results different? I hope you can get your answers.
******************/
Replenish:
answer:
The difference between $index++ and ++$index, $index++ is called the post-increment, and ++$index is called the pre-increment, although the result of the last $index will be +1. But there will be differences when passing variables.
$index = 1;
$m = $index++;
echo $index.'<br/>'; //The result is 2
echo $m.'<br/>'; //The result is 1. Because it is a post-increment, the initial $index=1 will be assigned to $m first, and then $index will be incremented by 1;
$index = 1;
$n = ++$index;
echo $index.'<br/>'; //The result is 2
echo $n;
This may not be easy to remember, so you must pay attention when using it. In the above question, I ignored this problem and caused $index to infinitely pass 0 values, which caused recursive locking.