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

Check if a Post exists in PHP

Publish Date:2025/04/13 Views:170 Category:PHP

PHP $_POST is a super global variable that can contain key-value pairs of HTML form data submitted through the post method. We will learn different ways to check $_POST if a and contains some data in this article. These methods will use iss

PHP with Ajax

Publish Date:2025/04/13 Views:139 Category:PHP

We will use PHP and ajax by printing a simple sum of two numbers 2 and . Also, print a php array in JSON. 3 object We will also use PHP with ajax by getting the HTML formatted output from the number division in PHP. Printing simple addition

Store Div Id in PHP variable and pass it to JavaScript

Publish Date:2025/04/13 Views:51 Category:PHP

This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s

Returns the article tag with ID from the action page

Publish Date:2025/04/13 Views:80 Category:PHP

Let's say you're in a login form and you enter the wrong information; in this case, you probably want to go back to the login page. PHP has a built-in function header() to redirect a page to a specific page. But what if the login page is at

Switching PHP versions on Ubuntu

Publish Date:2025/04/13 Views:78 Category:PHP

Different tasks may require running multiple versions of PHP. You may need to switch PHP versions by running two sites on the same server or testing older versions of code using outdated methods. We can switch PHP versions on Ubuntu using t

Resizing images in PHP

Publish Date:2025/04/13 Views:155 Category:PHP

In this tutorial article, we will discuss about resizing images in PHP. Load the image before resizing Before we can resize an image, we must first load it as an image resource in our script. This is file_get_contents() different from using

PHP upload image

Publish Date:2025/04/13 Views:61 Category:PHP

We can upload images in PHP using simple file upload operation, but first, php.ini file upload should be enabled from Files. This tutorial demonstrates how to upload images in PHP. php.ini Enable file upload from file in PHP to upload image

Creating a signature from Hash_hmac() and Sha256 in PHP

Publish Date:2025/04/13 Views:107 Category:PHP

PHP has one of the best encryption functions for data security. Hash_hmac() The encrypt function is one of the most famous encryptors. We'll show you how to use hash_hmac and sha256 encryptors to create 安全签名 one that you can store i

Updating PHP 7.x to 7.4 on CentOS

Publish Date:2025/04/13 Views:131 Category:PHP

This article shows the steps to update the PHP version from 7.x version to 7.4 in CentOS. How to Update PHP from 7.X to 7.4 in CentOS Update operating system packages. yum update -y Check your PHP version in CentOS. php -v Prints a list of

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial