>백엔드 개발 >PHP 튜토리얼 > php冒泡排序解决思路

php冒泡排序解决思路

WBOY
WBOY원래의
2016-06-13 12:54:36829검색

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

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

php 冒泡排序
------解决方案--------------------
$ar = array(24,1,3,2,8,3,5,6,10,13,27);<br />
bubble_sort($ar);<br />
<br />
function bubble_sort(&$ar)<br />
{<br />
   $ar_count = count($ar);<br />
   $temp = null;<br />
   for($i= 0 ; $i < $ar_count; $i ++)<br />
   {<br />
      for($j = 0 ; $j < $ar_count - $i - 1; $j++)<br />
      {<br />
          if($ar[$j] > $ar[$j+1])<br />
          {<br />
              $temp = $ar[$j];<br />
              $ar[$j] = $ar[$j+1];<br />
              $ar[$j+1] = $temp;<br />
          }<br />
      }<br />
echo join(',', $ar), PHP_EOL; //观察这里的输出<br />
   }<br />
}
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

大有优化的余地
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.