码迷,mamicode.com
首页 > 其他好文 > 详细

Bubble Sort

时间:2014-11-09 12:24:42      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   sp   for   div   

bubuko.com,布布扣

We have 8 numbers. Sort as ascend.

 

1st loop, we compare 7 times (for 8 numbers), and found the largest 8.

2nd loop, we compare 6 times (for 7 numbers), and found the largest 7.

...

 

1, 7, 8

2, 6, 7

3, 5, 6

4, 4, 5

5, 3, 4

6, 2, 3

7, 1, 2

 

In conclusion:

For sorting 8 numbers, we need an outer loop of 7 times, each time for finding a largest number; and an inner loop from comparing 7 times to comparing 1 time (as in the center column).

 

Implementation in PHP: 

 1 <?php
 2 /* bubble sort: 
 3     1. operate directly on the input array (&), not on a copy
 4     2. sort as ascend
 5 
 6     a is array
 7     m is length of a
 8     n is times of sort
 9     i/j is for-loop counter
10     w is for value swap
11 */
12 function sortBubble(&$a){
13     $m = count($a);
14     $n = $m - 1;
15     for($i=0; $i<$n; $i++){
16         for($j=0; $j<$n-$i; $j++){
17             if($a[$j] > $a[$j+1]){
18                 $w = $a[$j];
19                 $a[$j] = $a[$j+1];
20                 $a[$j+1] = $w;
21             }
22             else{
23                 // do nothing
24             }
25         }
26         // see the results after each outer loop
27         // echo implode(‘, ‘, $a).‘<br />‘;
28     }
29 }
30 
31 $arr = array(9, 5, 2, 7, 3);
32 sortBubble($arr);
33 echo implode(‘, ‘, $arr);
34 
35 // 2, 3, 5, 7, 9
37 ?>

 

Bubble Sort

标签:style   blog   http   io   color   ar   sp   for   div   

原文地址:http://www.cnblogs.com/crepesofwrath/p/4084714.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!