PHP bubble algorithm (Recursive Implementation) and bubble Recursion
Implementation
Copy codeThe Code is 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 ));
Result:
Copy codeThe Code is as follows:
Array ([0] => 1 [1] => 3 [2] => 4 [3] => 5 [4] => 6 [5] => 7 [6] => 8 [7] => 9 [8] => 12)
Problem:
When trying this implementation, I encountered a problem that has not yet been solved.
Here:
Copy codeThe Code is as follows:
$ Index ++;
Return maoPao ($ array, $ index );
// Return maoPao ($ array, $ index ++ );
/******************
If you use the third row directly, instead of $ index ++, and then ruturn, it will enter an endless loop. I output $ index at the beginning of the function, all of which are 0, that is to say, the parameter passed to the recursive function after $ index ++ is not the result of $ index ++ (that is, $ index = $ index + 1 ).
MaoPao ($ array, $ index ++) is not a brief description of $ index ++; return maoPao ($ array, $ index);. Why are the two results different, I hope you can answer this question.
******************/
Supplement:
Answer:
Copy codeThe Code is as follows:
The difference between $ index ++ and ++ $ index is that $ index ++ is called post increment and ++ $ index is called pre increment, although the final $ index result will all be + 1. However, when variables are passed, they may be different.
$ Index = 1;
$ M = $ index ++;
Echo $ index. '<br/>'; // The result is 2.
Echo $ m. '<br/>'; // The result is 1. because it is post-increment, the initial $ index = 1 is first assigned to $ m, and then $ index increases by 1;
$ Index = 1;
$ N = ++ $ index;
Echo $ index. '<br/>'; // The result is 2.
Echo $ n; // The result is 2. Because it is a previous increment, $ index + 1 is executed first, and then assigned to $ n;
This may not be easy to remember, so you must pay attention when using it. In the above problem, I ignored this problem and caused the infinite 0 value passed by $ index to lock the recursion.