现在的位置: 首页 > 综合 > 正文

PHP冒泡排序

2012年08月20日 ⁄ 综合 ⁄ 共 478字 ⁄ 字号 评论关闭
 1 <html>
 2     <body>        
 3         <?php
 4             function bubble_sort($array) {
 5                 for($i = 0; $i < count($array) - 1; $i++) {    //$i为已经排过序的元素个数
 6                     for($j = 0; $j < count($array) - 1 - $i; $j++) {    //$j为需要排序的元素个数,用总长减去$i
 7                         if($array[$j] > $array[$j + 1]) {    //按升序排序
 8                             $temp = $array[$j];
 9                             $array[$j] = $array[$j + 1];
10                             $array[$j + 1] = $temp;
11                         }
12                     }
13                 }
14                 return $array;
15             }
16             
17             $array = array(5, 1, 4, 7, 7, 9, 0, 11);
18             var_dump(bubble_sort($array));
19         ?>
20     </body>
21 </html>

页面输出

array(8) { [0]=> int(0) [1]=> int(1) [2]=> int(4) [3]=> int(5) [4]=> int(7) [5]=> int(7) [6]=> int(9) [7]=> int(11) }

抱歉!评论已关闭.