phpバブルソート

2440 ワード

<?php
// ==============PHP     ==============
header("Content-type:text/html;charset=utf-8"); 

$arr=array(1,11,10,12,21,3);  
function mpsort($arr){  
    $n = count($arr);  
    for($i = 0; $i < $n; $i++){  //      。  
        for($j = 0; $j < $n-$i-1; $j++){   
            if($arr[$j] > $arr[$j+1]){    //                
                $tmp = $arr[$j];        //                   1 2 3 12 13   
                $arr[$j] = $arr[$j+1];  
                $arr[$j+1] = $tmp;  
            }  
        }  
    }  
    return $arr;  
}  

echo '<pre>';  
print_r(mpsort($arr));  
echo '</pre>';  


//   ====================     ======================
/*
$arr=array(5,4,2,1,3);  
print_r(mpsort($arr));  
function mpsort($arr){
    $n = count($arr);
    $num = 1;
    for ($i=0; $i < $n; $i++) { 
          for ($j=0; $j < $n-$i-1; $j++) {
              if($arr[$j] > $arr[$j+1] ){
                  print_r($arr);
                  echo  $num++;
                  echo "<br>";
                  $tmp = $arr[$j];
                  $arr[$j]  = $arr[$j+1];
                  $arr[$j+1] = $tmp;
              }else{
                print_r($arr);
                echo "-----   ------  ";
                echo $num++;
                echo "<br>";
              }
          }
    }
}
*/

// $i     0  1  2  3  4    $i      。
// $j <  4  3  2  1  0    $j     。         10 。

/*              。
Array ( [0] => 5 [1] => 4 [2] => 2 [3] => 1 [4] => 3 ) 1
Array ( [0] => 4 [1] => 5 [2] => 2 [3] => 1 [4] => 3 ) 2
Array ( [0] => 4 [1] => 2 [2] => 5 [3] => 1 [4] => 3 ) 3
Array ( [0] => 4 [1] => 2 [2] => 1 [3] => 5 [4] => 3 ) 4
Array ( [0] => 4 [1] => 2 [2] => 1 [3] => 3 [4] => 5 ) 5
Array ( [0] => 2 [1] => 4 [2] => 1 [3] => 3 [4] => 5 ) 6
Array ( [0] => 2 [1] => 1 [2] => 4 [3] => 3 [4] => 5 ) 7
Array ( [0] => 2 [1] => 1 [2] => 3 [3] => 4 [4] => 5 ) 8
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) -----   ------ 9
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) -----   ------ 10
*/
/*
   for     $n-$i-1      ,       2( 0  ),      2      。  $j for       2     ($j       )。
      $j    ,  $j+1          ,              ,        for     $j   ,    。
*/