JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

Learning the sorting algorithm - Binary Insertion Sort

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

This article follows the insertion sort (concept article) and presents the implementation steps and implementation code of the binary insertion sort

Binary Insertion Sort Algorithm Steps

  1. Treat the first element of the first sequence to be sorted as an ordered sequence, and the second element to the last element as an unsorted sequence.
  2. Scan the unsorted sequence from beginning to end, and insert each scanned element into the appropriate position of the ordered sequence. Binary insertion sort uses the binary search method to find the appropriate position in the ordered sequence to insert the unsorted elements. (One thing to note here is that if there is an element in the ordered sequence that is equal to the element to be inserted, the element to be inserted will be found after this element. This way of insertion sorting is stable. If it is inserted in front of this element, then this way of insertion sorting is unstable)

Implementation code (PHP code)

$arr1 = array(15,77,23,43,90,87,68,32,11,22,33,99,88,66,44,113,224,765
,980,159,456,7,998,451,96,0,673,82,91,100);
for($i=1;$i<count($arr);$i++){
    if($arr[$i]<$arr[$i-1]){
        //使用二分查找法查找适当的位置
        $low = 0;
        $high = $i-1;
        $pos = floor(($low+$high)/2);
        $key = $arr[$i];
        while($low<$high){
            if($arr[$pos]>$key){
                $high = $pos-1;
            }elseif($arr[$pos]<=$key){
                $low = $pos+1;
            }
            $pos = floor(($low+$high)/2);
        }
        //二分查找法结束
        if($arr[$pos]>$arr[$i]){
            $pos = $pos-1;
        }
        for($j=$i-1;$j>$pos;$j--){
            $arr[$j+1]=$arr[$j];
        }
        $arr[$j+1] = $key;
    }
}

The above is the implementation code of Binary Insertion Sort. From the code, we can see that the only difference between Binary Insertion Sort and Direct Insertion Sort is the code for finding the position. The rest are the same. Binary Insertion Sort needs to move the same elements as Direct Insertion Sort. Therefore, its time complexity is also O(n²).

But further analysis shows that even though the time complexity of the two is the same, binary insertion sort is faster than direct insertion sort overall. The following is a test I did (the data required here cannot be the data in the above code. Here I constructed an array of 100 data for testing)

$arr = array(15,77,23,43,90,87,68,32,11,22,33,99,88,66,44,113,224,765,980,
159,456,7,998,451,96,0,673,82,91,100,36,57,1334,5567,4432,11178,9997,88851,
4449,33332,9992,76853,67434,1239,98716,5349,90718,3589,213450,6754,24,
562,77,16,127,361,572,13343,55674,44325,1117,99979,88850,44491,3333,99923,
7685,6743,12395,9871,53497,9071,35899,21345,67541,24,56,774,16,127,111,112,
113,114,115,116,117,118,119,110,101,102,103,104,105,106,107,108,109,1000);

The direct insertion sort code uses the following paragraph

for($i=1;$i<count($arr);$i++){
    $p = $arr[$i];
    for($j=$i-1;$j>=0;$j--){
        if($arr[$j]>$p){
            $arr[$j+1] = $arr[$j];
        }else{
            break;
        }
    }
    $arr[$j+1] = $p;
}

Based on the same set of data, we run these two codes multiple times and record the time taken for each. The following is the time comparison for each time. The one above is binary insertion sort and the one below is direct insertion sort.

From the above comparisons, we can find that the time required for binary insertion is shorter than that required for direct insertion. The larger the amount of data, the more obvious the time difference between the two methods. Therefore, in actual projects, if we really need to use the insertion sort algorithm, I personally recommend using binary insertion sort. Binary insertion may not be better than direct insertion in terms of space usage, because binary insertion requires more other variables than direct insertion. So when we only have dozens of data, run the above two codes again, you will be surprised to find that the time of the former (binary insertion) is actually longer than the latter (direct insertion). This is because so many variables need to allocate memory for them, and the time spent accounts for a large proportion of the entire running process, so the time of the former is longer than the latter. However, as the amount of data increases, the proportion of time allocated for variables gradually becomes smaller and smaller, which can be almost ignored. Therefore, when the amount of data is large, the time of the former is shorter than the latter. Moreover, with the current hardware level, in my opinion, the advantage of time can make up for the relative lack of space. If in actual situations our data volume really reaches the point where the advantage of time can no longer make up for the space, then there are other sorting algorithms for us to choose.

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