As soon as we learned programming, we knew various sorting algorithms. now let's take a look at the usage of the php bubble algorithm in practical applications. for a friend in need, let's take a simple reference. the code is as follows: & lt ;? Phpheader (& amp;
As soon as we learned programming, we knew various sorting algorithms. now let's take a look at the usage of the php bubble algorithm in practical applications. for a friend in need, let's take a simple reference. the code is as follows:
- Header ('content-Type: text/html; charset = utf-8 ');
- // Simple bubble algorithm 0 1 2 3 4
- $ A = array (5, 4, 3, 2, 1); // 5
- Echo "comparison 54321 ";
- Function mp ($ a) {// if the value is an array
- // I = 1 I <5 I ++
- For ($ I = 0; $ I < li><>
- /* J = 3 j < li><>
- * Why is it-2?
- * Because the array starts from 0,-1 is required.
- * Then we will compare the last and last two digits in a moment, so we need-2.
- * Of course, you can change $ a [j + 1] to $ a [j] and change $ a [j] to $ a [j-1 ].
- */
- For ($ j = count ($ a)-2; $ j >=$ I; $ j --){
- // Compare the maximum number of digits in the array with the second largest.
- If ($ a [$ j + 1] <$ a [$ j]) {
- Echo $ a [$ j + 1], '------ less than -----', $ a [$ j], '---------- before sorting:', fn ($ );
- // Change the location if the largest value is smaller than the second largest value
- $ Tmp = $ a [$ j + 1];
- $ A [$ j + 1] = $ a [$ j];
- $ A [$ j] = $ tmp;
- Echo '------------ arranged:', fn ($ ),'
';
- }
- }
- }
- Return $;
- }
- Echo fn (mp ($ ));
-
- Function fn ($ arr ){
- Foreach ($ arr as $ value ){
- Echo $ value;
- }
- }
- ?>