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. If you need it, let's take a simple reference.
| The Code is as follows: |
Copy code |
|
<? Php
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 "compared to 54321 <br/> Function mp ($ a) {// if the value is an array
// I = 1 I <5 I ++
For ($ I = 0; $ I <count ($ a); $ I ++ ){
/* J = 3 j <I j --
* 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 ($ a), '<br> }
}
}
Return $;
}
Echo fn (mp ($ ));
Function fn ($ arr ){
Foreach ($ arr as $ value ){
Echo $ value;
}
}
?>
|