Algorithm-Bubble Sort (implemented by PHP code)

Three minutes to thoroughly understand bubble sort

1. Principle: Compare two adjacent elements and swap the element with the larger value to the right

2. Idea: Compare two adjacent numbers in turn, put the smaller number in the front and the larger number in the back.

(1) The first comparison: first compare the first and second numbers, putting the decimal number in the front and the big number in the back.

(2) Compare the 2nd and 3rd numbers, put the decimal number at the front and the big number at the back.

(3) Continue like this, know the two numbers that are compared to the last, put the decimal number in the front and the big number in the back, repeat the steps until all sorts are completed

(4) After the previous comparison is completed, the last number must be the largest number in the array, so when the second comparison is performed, the last number is not included in the comparison.

(5) After the second round of comparison is completed, the penultimate number must also be the penultimate number in the array, so in the third round of comparison, the last two numbers are not included in the comparison.

(6) By analogy, the number of comparisons in each pass decreases sequentially

3. Example:
(1) To sort the array: [10,1,35,61,89,36,55]
Insert picture description here
(2) The first sorting:

The first sort: 10 and 1, 10 is greater than 1, exchange positions [1,10,35,61,89,36,55]

Second time sorting: compare 10 and 35, 10 is less than 35, and do not swap positions [1,10,35,61,89,36,55]

The third round of sorting: compare 35 and 61, 35 is less than 61, do not swap positions [1,10,35,61,89,36,55]

The fourth round of sorting: compare 61 and 89, 61 is less than 89, do not swap positions [1,10,35,61,89,36,55]

Fifth pass sort: compare 89 and 36, 89 is greater than 36, exchange positions [1,10,35,61,36,89,55]

The sixth time sequence: compare 89 and 55, 89 is greater than 55, exchange positions [1,10,35,61,36,55,89]

A total of six comparisons were made in the first pass, and the sort result: [1,10,35,61,36,55,89]
      Insert picture description here
(3) The second pass was sorted:

The first sorting: 1 and 10 are compared, 1 is less than 10, and positions 1,10,35,61,36,55,89 are not exchanged

The second sort: 10 and 35 comparison, 10 is less than 35, do not swap positions 1,10,35,61,36,55,89

The third order: 35 and 61 comparison, 35 is less than 61, do not exchange positions 1,10,35,61,36,55,89

Fourth order: compare 61 and 36, 61 is greater than 36, exchange positions 1,10,35,36,61,55,89

Fifth order: compare 61 and 55, 61 is greater than 55, exchange positions 1,10,35,36,55,61,89

A total of 5 comparisons were made in the second pass, and the sorted results: 1,10,35,36,55,61,89

(4) The third time sequence:

1 is compared with 10, 1 is less than 10, no exchange of positions 1,10,35,36,55,61,89

The second sort: 10 and 35 comparison, 10 is less than 35, do not swap positions 1,10,35,36,55,61,89

The third sort: 35 and 36 comparison, 35 is less than 36, do not exchange positions 1,10,35,36,55,61,89

Fourth order: compare 36 and 61, 36 is less than 61, and do not swap positions 1,10,35,36,55,61,89

In the third round, a total of 4 comparisons were made, and the sorting results: 1,10,35,36,55,61,89

So far, the position is already in order.
4. Algorithm analysis:

(1) It can be seen that: N numbers need to be sorted, a total of N-1 passes are sorted, and the number of sorts for each i pass is (Ni) times , so double loop statements can be used, the outer layer controls how many times the loop is, the inner layer Control the number of cycles per pass

(2) The advantage of bubble sorting: every time sorting is performed, there will be less comparison, because every time sorting is performed, a larger value will be found. As in the above example: after the first pass, the last number must be the largest number. When the second pass is sorted, you only need to compare other numbers except the last number, and you can also find the largest number. The number of is ranked behind the number that participated in the second round of comparison. In the third round of comparison, you only need to compare the other numbers except the last two numbers, and so on... That is to say, there is no comparison, every time Comparing less once per trip reduces the amount of algorithms to a certain extent.

(3) Time complexity

1. If our data is in positive order, we only need to take one trip to complete the sorting. The required comparison times C and recorded movement times M both reach the minimum, namely: Cmin=n-1; Mmin=0; Therefore, the best time complexity for bubble sort is O(n).

2. If unfortunately our data is in reverse order, we need to sort by n-1 times. Each sequence requires ni comparisons (1≤i≤n-1), and each comparison must move the record three times to reach the exchange record position. In this case, the number of comparisons and moves reached the maximum:
    Insert picture description here
In summary: the total average time complexity of bubble sorting is: O(n2), and the time complexity is independent of the data status.

PHP code implementation

1. Basic code implementation

    /**
     * 冒泡排序
     * @param $arr
     */
    public function bubbleSort($arr)
    {
    
    
        $length = count($arr);
        for ($i=1;$i<$length;$i++) {
    
     //需要执行 length-1 趟排序
            for ($j=0;$j<$length-$i;$j++) {
    
     //每趟需要执行 length-i 次比较
                //两两比较相邻元素
                if($arr[$j] > $arr[$j+1]){
    
    
                    $this->swap($arr, $j,$j+1);
                }
            }
        }
        return $arr;
    }

    /**
     * 数组元素交换位置
     * @param array $arr
     * @param $a
     * @param $b
     */
    function swap(array &$arr, $a, $b)
    {
    
    
        $temp = $arr[$a];
        $arr[$a] = $arr[$b];
        $arr[$b] = $temp;
    }

2. Sorting optimization

You can introduce a flag to determine whether you need to enter the next cycle. When there is no data exchange, it means that the data is already in order, and you don't need to enter the next cycle.

    /**
     * 冒泡排序
     * @param $arr
     */
    public function bubbleSort($arr)
    {
    
    
        $length = count($arr);
        $flag = true; //是否需要进行下一趟排序标志
        if ($flag) {
    
    
            for ($i=1;$i<$length;$i++) {
    
     //需要执行 length-1 趟排序
                $flag = false; //每次进入一趟循环默认下一次不再循环
                for ($j=0;$j<$length-$i;$j++) {
    
     //每趟需要执行 length-i 次比较
                    //两两比较相邻记录
                    if($arr[$j] > $arr[$j+1]){
    
    
                        $this->swap($arr, $j,$j+1);
                        $flag = true;  //当有数据发生交换,说明还需要下一趟排序
                    }
                }
            }
        }
        return $arr;
    }

    /**
     * 数组元素交换位置
     * @param array $arr
     * @param $a
     * @param $b
     */
    function swap(array &$arr, $a, $b)
    {
    
    
        $temp = $arr[$a];
        $arr[$a] = $arr[$b];
        $arr[$b] = $temp;
    }

Reference address for this article

  1. https://www.jb51.net/article/138558.htm
  2. https://www.cnblogs.com/bigdata-stone/p/10464243.html

Guess you like

Origin blog.csdn.net/magentodaddy/article/details/108600523