Home  >  Article  >  Backend Development  >  A simple PHP bubble sort algorithm_PHP tutorial

A simple PHP bubble sort algorithm_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 16:59:40993browse

When we first learned programming, we knew various sorting algorithms. Now let’s take a look at how the PHP bubble algorithm is used in practical applications. Friends in need can simply refer to it.

The code is as follows Copy code

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 "Compare 54321


";
function mp($a){ //Pass value if it is an array
//i=1 i<5 i++
for($i=0;$i                                     /* j=3 j * Why is there -2 here
* Because the array starts from 0, it needs to be -1
                    * Then, we need to compare the last digit and the second to last digit, so -2
* Of course -1 is also possible, just change $a[j+1] to $a[j] and then change $a[j] to $a[j-1]
                     */
for ($j=count($a)-2;$j>=$i;$j--){
//Judge the largest number of digits in the array and compare it with the second largest one
If ($a[$j+1]<$a[$j]){
echo $a[$j+1],'------is less than-----',$a[$j],'----------before arrangement:',fn( $a);
//If the largest one is smaller than the second largest one, change the position
                                                                                                                                                                                                      echo '------------After arrangement:',fn($a),'

';
                                                                                                             }                                                                                          }
                                                                                                                                                }
         return $a;
}

echo fn(mp($a));


function fn($arr){
foreach ($arr as $value){
echo $value;
                                                                      }

?>

http://www.bkjia.com/PHPjc/631311.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631311.htmlTechArticleWhen we first learned programming, we knew various sorting algorithms. Now let’s look again at the practical application of the PHP bubble algorithm Let’s take a look at the usage. Friends in need can simply refer to it. The code is as follows Copy...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn