欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

Bubble Sort,bubblesort_PHP教程

程序员文章站 2022-05-22 21:34:47
...

Bubble Sort,bubblesort

Bubble Sort,bubblesort_PHP教程

8 numbers. Sort as ascend.

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

2nd loop, 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 outer loop, n-i is times of comparing for each outer loop
 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
相关标签: 冒泡排序