日期:2014-05-17  浏览次数:20369 次

php冒泡排序
搜索了哈php冒泡排序,网上写的不知道第二层循环都是递减的,很不符合我的习惯,既然是冒泡肯定是从下往上啊,所以索性自己写了个分享哈!


<?php
  $ar = array(1,3,2,8,3,5,6,10,13,27,24);
bubble_sort($ar);
print_r($ar);
 function bubble_sort(&$ar)
{
   $ar_count = count($ar);
   $temp = null;
   for($i= 0 ; $i < $ar_count; $i ++)
   {
      for($j = 0 ; $j < $ar_count - $i - 1; $j++)
      {
          if($ar[$j] > $ar[$j+1])
          {
              $temp = $ar[$j];
              $ar[$j] = $ar[$j+1];
              $ar[$j+1] = $temp;
          }
      }
   }
}
php 冒泡排序

------解决方案--------------------
$ar = array(24,1,3,2,8,3,5,6,10,13,27);
bubble_sort($ar);

function bubble_sort(&$ar)
{
   $ar_count = count($ar);
   $temp = null;
   for($i= 0 ; $i < $ar_count; $i ++)
   {
      for($j = 0 ; $j < $ar_count - $i - 1; $j++)
      {
          if($ar[$j] > $ar[$j+1])
          {
              $temp = $ar[$j];
              $ar[$j] = $ar[$j+1];
              $ar[$j+1] = $temp;
          }
      }
echo join(',', $ar), PHP_EOL; //观察这里的输出
   }
}
1,3,2,8,3,5,6,10,13,24,27
1,2,3,3,5,6,8,10,13,24,27 到这里排序已经结束
1,2,3,3,5,6,8,10,13,24,27 从这里开始,以下都是无效劳动
1,2,3,3,5,6,8,10,13,24,27
1,2,3,3,5,6,8,10,13,24,27
1,2,3,3,5,6,8,10,13,24,27
1,2,3,3,5,6,8,10,13,24,27
1,2,3,3,5,6,8,10,13,24,27
1,2,3,3,5,6,8,10,13,24,27
1,2,3,3,5,6,8,10,13,24,27
1,2,3,3,5,6,8,10,13,24,27

大有优化的余地