JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

The road to learning sorting algorithms - merge sort

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

Let's first look at the definition of merge sort

Merge sort is an effective sorting algorithm based on the merge operation. This algorithm is a very typical application of the Divide and Conquer method. Merge the ordered subsequences to obtain a completely ordered sequence; that is, first make each subsequence ordered, and then make the subsequence segments ordered. If two ordered lists are merged into one ordered list, it is called a two-way merge.

Simply put, it merges two ordered lists into one ordered list.

Let's first understand the process of merge sort through the following figure.

Merge sort process

Let's look at the steps of how to decompose and then merge

  1. Apply for space whose size is the sum of the two sorted sequences. This space is used to store the merged sequence.
  2. Set two pointers, the initial positions of which are the starting positions of the two sorted sequences.
  3. Compare the elements pointed to by the two pointers, select the relatively small element and put it into the merge space, and move the pointer to the next position
  4. Repeat step 3 until a pointer reaches the end of the sequence
  5. Copy all remaining elements of the other sequence directly to the end of the merged sequence

Finally, we implemented the merge sort algorithm using PHP

function Merge($arr,$l,$m,$r){
    $t = $arr;
    $start = $l;
    $end = $m+1;
    while($l<=$r){
        if($l>$m||$end>$r) break;
        if($arr[$l]<$arr[$end]){
            $t[$start++] = $arr[$l++];
        }else{
            $t[$start++] = $arr[$end++];
        }
    }
    if($l<=$m){
        $s = $l;
        $e = $m;
    }elseif($r>=$end){
        $s = $end;
        $e = $r;
    }
    while($s<=$e){
        $t[$start++] = $arr[$s++];
    }
    $arr = $t;
    return $arr;
}
function MergeSort(&$arr,$l,$r){
   if($r <= $l) return ;
   $m = floor(($l+$r)/2);
   MergeSort($arr,$l,$m);
   MergeSort($arr,$m+1,$r);
   $arr = Merge($arr,$l,$m,$r);
}
$arr = array(10,6,8,23,4,1,17,56,32,50,11,9);
MergeSort($arr,0,count($arr)-1);
print_r($arr);

The above code is implemented using a recursive mechanism. Of course, it can also be implemented in a non-recursive form. You can refer to the article "Merge Sort (Non-recursive Implementation)" .

Using PHP to implement merge sort, according to the above code, the code is relatively cumbersome. PHP has its own characteristics, and can use less code to implement merge sort. However, the above code can better reflect the entire decomposition and merging process. So if you are learning the merge sort algorithm, it is recommended to use the above code. Although the code is cumbersome, it is very helpful for understanding the merge sort process.

For a more detailed merge sort algorithm, I have written a new article to fully understand the merge sort algorithm , which you can refer to.

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

Grouping and Sorting in Pandas

Publish Date:2025/04/12 Views:90 Category:Python

This tutorial explored the concept of grouping data in a DataFrame and sorting it in Pandas. Grouping and Sorting DataFrame in Pandas As we know, Pandas is an advanced data analysis tool or package extension in Python. Most of the companies

Sort a collection by date in MongoDB

Publish Date:2025/04/11 Views:64 Category:MongoDB

In this MongoDB tutorial, the problem of sorting a collection in MongoDB is discussed. The different ways to sort a collection in the database are briefly explained. Using sort() function in MongoDB This problem is solved using the MongoDB

Sort by RAND in MySQL

Publish Date:2025/04/09 Views:176 Category:MySQL

Summary: in this tutorial, we will learn how to shuffle or sort the values ​​or records of a table in MySQL. Most businesses and organizations that use MySQL for data analysis or visualization need to sort different table values ​​o

Linux sort command sort

Publish Date:2025/04/08 Views:172 Category:OPERATING SYSTEM

The sort command is a commonly used sorting command in Linux , and it is also a pipeline command . In order to ensure that future instances can get the sorting results we want, we need to set the following # export LC_ALL=C Okay, next we wi

Sort Files by Size in Linux

Publish Date:2025/04/06 Views:191 Category:OPERATING SYSTEM

Sometimes you want to do some deep cleaning of your system by finding unnecessary large files and deleting them or removing files that are smaller than a predetermined size, such as logs. Linux provides various utilities that can help us fi

Sorting Arrays in Bash

Publish Date:2025/03/23 Views:74 Category:OPERATING SYSTEM

Sorting an array is a very common task in any programming language. In Bash scripting, we can also accomplish this task in two different ways. The first one uses any sorting algorithm and the second one uses a built-in keyword in Bash scrip

Sort data based on the second column of a file in Bash

Publish Date:2025/03/22 Views:87 Category:OPERATING SYSTEM

This article explains how to sort data based on the second column of a file in bash. Overview of the Sort Command in Bash Sort files using the sort command, which places records in a specific order. By default, the sort command sorts files

Learning the Sorting Algorithm - Insertion Sort (Concepts)

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

What is "insertion sort"? The concept is as follows: each time a record to be sorted is inserted into the previously sorted sequence according to its key size, until all records are inserted. Concepts are always somewhat abstract, and can a

Learning path of sorting algorithm - direct insertion sort

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

This article follows up on Insertion Sort (Concepts) and presents the implementation steps and code for direct insertion sort. Since the Concepts section already has a large number of illustrations, it would be a bit long-winded to provide

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial