JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

The road to learning sorting algorithms - bubble sort

Author:JIYIK Last Updated:2025/03/19 Views:

Bubble sort is also a simple and intuitive sorting algorithm. The idea is that it repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if they are in the wrong order. The work of visiting the sequence is repeated until there is no need to swap, that is, the sequence has been sorted. The name of this algorithm comes from the fact that smaller elements will slowly "float" to the top of the sequence through swapping.

Let's take a look at this bubbling process through a simple diagram.

The starting position is 0, and the two adjacent elements are compared in sequence. If the previous element is greater than the next element, they are swapped.

We can see that the number of bubbling passes is equal to the number of elements in the sequence to be sorted. However, in practice, we can reduce the number of bubbling passes according to the actual situation.

Take the above example, we can see that the sequence is already ordered after the fourth bubbling process. The fifth and sixth bubbling processes did not produce any element swaps. So we can judge that if no element swaps are produced in a bubbling process, we terminate the entire bubbling process. In this way, the final sequence is also ordered.

The reaction in the program is to set a flag at the beginning of each bubbling, which defaults to false. When an exchange occurs, the flag is set to true. After the bubbling process ends, we use this flag to determine whether an exchange occurs. If no exchange occurs, we end the entire bubbling process directly. Otherwise, continue to the next bubbling process.

According to the above picture, let's look at the steps to implement the text of bubble sort

1) Compare adjacent elements. If the first is greater than the second, swap them.
2) Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. When this is done, the last element will be the largest number.
3) Repeat the above steps for all elements except the last one.
4) Keep repeating the above steps for fewer and fewer elements each time, until there are no pairs of numbers left to compare.

Finally, we need to convert the text steps into code implementation

/**
 * 交换函数
 */
function swap(&$arr,$a,$b){
    $t = $arr[$a];
    $arr[$a] = $arr[$b];
    $arr[$b] = $t;
}
function BubbleSort(&$arr){
    $end = count($arr)-1;
    while($end>0){
        for($i=0;$i<$end;$i++){
            if($arr[$i]>$arr[$i+1]){
                swap($arr,$i,$i+1);
            }
        }
        $end--;
    }
}
$arr = array(10,6,8,23,4,1,17,56,32,50,11,9);
BubbleSort($arr);
print_r($arr);

The above code goes through all the bubbling processes. Next, we only need to make a simple modification to the BubbleSort function to implement the flag we mentioned above to determine whether an exchange occurs.

function BubbleSort(&$arr){
    $end = count($arr)-1;
    while($end>0){
        $flag = false;  //每次冒泡前 初始化标志位为false
        for($i=0;$i<$end;$i++){
            if($arr[$i]>$arr[$i+1]){
                swap($arr,$i,$i+1);
                $flag = true;  //有交换产生 将标志位置为true
            }
        }
        if(!$flag) break;  //如果没有交换产生 则直接跳出循环
        $end--;
    }
}

In fact, there is no obvious difference between programs with and without flags when the amount of data is small, and the time taken should not be much different. But when the amount of data is large, the difference becomes very obvious. But then again, bubble sort is not the best sorting algorithm. Its efficiency is lower than other sorting algorithms, and its time complexity is O(n²). So in actual situations, if the amount of data is large, we may not necessarily choose bubble sort to implement sorting.

But I personally think that bubble sort and selection sort can be said to be the basis of other sorts, so it is necessary for us to understand bubble sort.

I hope this article is helpful to you.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

The road to learning sorting algorithms - heap sort

Publish Date:2025/03/19 Views:145 Category:ALGORITHM

Like other sorting algorithms, let's first look at the definition of heap sort. Heapsort : refers to a sorting algorithm designed using the heap data structure. A heap is a structure that approximates a complete binary tree and satisfies th

Core code of commonly used sorting algorithms

Publish Date:2025/03/19 Views:122 Category:ALGORITHM

In the article "Common Sorting Algorithms", we briefly introduced the ideas and implementation steps of various sorting algorithms. In this article, I will share the core codes of these sorting algorithms with you. The complete code of all

Learning the Sorting Algorithm - Radix Sorting (LSD)

Publish Date:2025/03/19 Views:177 Category:ALGORITHM

Radix Sort : It is a non-comparative integer sorting algorithm. The basic principle of radix sorting is to group integers according to the number of digits in the integer. In the grouping process, the missing digits are filled with 0. Accor

The road to learning sorting algorithms - Radix Sort (MSD)

Publish Date:2025/03/19 Views:140 Category:ALGORITHM

In the article "Radix Sort (LSD)" , we explained the concept and efficiency analysis of radix sort. We will not repeat it in this article. You can refer to that article to get a general understanding of the idea of ​​radix sort. Next, w

PHP finds the common prefix of multiple strings [Case]

Publish Date:2025/03/19 Views:94 Category:ALGORITHM

This article shares with you the application of a small algorithm - finding the common prefix of a string array: array ( 'abcdefg' , 'abcdfio' , 'abcdqle' ) In the above array string, the common prefix is ​​'abcd'. The first thing that

First contact with CGI

Publish Date:2025/03/18 Views:51 Category:NETWORK

Since I am a PHP programmer, I often have to build a PHP operating environment. The popular nginx+php environment is very popular, and the mode it adopts is the FastCGI method, so I spent some time to learn about FastCGI. CGI (Common Gatewa

PHP cluster session sharing

Publish Date:2025/03/18 Views:124 Category:NETWORK

The concept of cluster is not complicated. It is actually multiple computers working together for the same goal. In Web applications, multiple servers provide services for a site. The first step to build a PHP cluster is to set up load bala

PHP+ajax to achieve cross-domain single sign-on

Publish Date:2025/03/16 Views:145 Category:NETWORK

We have previously introduced the principle of cross-domain single sign-on in "Detailed explanation of the implementation methods of three situations of SSO single sign-on" . Here we will introduce how to implement single sign-on using PHP

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial