Home  >  Article  >  Backend Development  >  php冒泡排序解决思路

php冒泡排序解决思路

WBOY
WBOYOriginal
2016-06-13 11:13:51902browse

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

大有优化的余地
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