Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Merge Sort

Merge Sort

Merge sort (English: Merge sort, or mergesort) is an efficient sorting algorithm based on the merge operation.

Merge sort is a very typical application of the Divide and Conquer method. It merges already ordered subsequences to obtain a fully ordered sequence; that is, first make each subsequence ordered, then make the segments between subsequences ordered. Merging two ordered lists into one ordered list is called two-way merge.

Imagine you need to organize a completely shuffled deck of cards. An efficient approach is: first split the deck into two small piles, organize each pile separately, and finally merge the two already ordered piles into one fully ordered deck.Merge Sort It is precisely based on this divide and conquer idea that this classic sorting algorithm is designed.

Its core operations can be summarized in two steps:

Applicability Notes

Merge sort is suitable for scenarios with large data volumes and requirements for stability.

Merge sort is a stable sorting algorithm (i.e., the relative order of equal elements remains unchanged after sorting), and its time complexity is O(n log n) in all cases, making it very efficient for large-scale data. However, its space complexity is O(n) because the merge process requires extra arrays to temporarily store data.

The flowchart below clearly shows the entire process of divide and conquer in merge sort:

Process Diagram

Merge sort is an instance of a recursive algorithm. The basic operation in this algorithm is merging two sorted arrays: take two input arrays A and B, one output array C, and three counters i, j, k, whose initial positions are placed at the beginning of their respective arrays.

Copy the smaller of A[i] and B[j] to the next position in C, and advance the relevant counter by one step.

When one of the two input arrays is exhausted, copy the remaining part of the other array into C.

Top-down merge sort, recursive grouping diagram:

Perform merge sort on the data grouped in twos in the third row

Perform merge sort on the data grouped in fours in the second row

Perform merge sort on the whole

Java Example Code

Source code package download:Download

MergeSort.java file code:

public

class

MergeSort

{

   

// Merge the two parts arr[l...mid] and arr[mid+1...r]

   

private

static

void

merge

(

Comparable

[

]

arr,

int

l,

int

mid,

int

r

)

{

       

Comparable

[

]

aux

=

Arrays

.

copyOfRange

(

arr, l, r

1

)

;

       

// Initialization: i points to the starting index l of the left half; j points to the starting index mid+1 of the right half

       

int

i

=

l, j

=

mid

1

;

       

for

(

int

k

=

l

;

k

<=

r

;

k

++

)

{

           

if

(

i

mid

)

{

 

// If all elements of the left half have been processed

                arr

[

k

]

=

aux

[

j

l

]

;

                j

++;

           

}

else

if

(

j

r

)

{

 

// If all elements of the right half have been processed

                arr

[

k

]

=

aux

[

i

l

]

;

                i

++;

           

}

else

if

(

aux

[

i

l

]

.

compareTo

(

aux

[

j

l

]

)

<

0

)

{

// The element pointed to in the left half < The element pointed to in the right half

                arr

[

k

]

=

aux

[

i

l

]

;

                i

++;

           

}

else

{

 

// The element pointed to in the left half >= the element pointed to in the right half

                arr

[

k

]

=

aux

[

j

l

]

;

                j

++;

           

}

       

}

   

}

   

// Recursively use merge sort to sort the range arr[l...r]

   

private

static

void

sort

(

Comparable

[

]

arr,

int

l,

int

r

)

{

       

if

(

l

=

r

)

{

           

return

;

       

}

       

int

mid

=

(

l

r

)

/

2

;

        sort

(

arr, l, mid

)

;

        sort

(

arr, mid

1

, r

)

;

       

// For arr[mid] <= arr[mid+1], do not merge

       

// Very effective for nearly ordered arrays, but for general cases there is a certain performance loss

       

if

(

arr

[

mid

]

.

compareTo

(

arr

[

mid

1

]

)

0

)

            merge

(

arr, l, mid, r

)

;

   

}

   

public

static

void

sort

(

Comparable

[

]

arr

)

{

       

int

n

=

arr.

length

;

        sort

(

arr,

0

, n

1

)

;

   

}

   

// Test MergeSort

   

public

static

void

main

(

String

[

]

args

)

{

       

int

N

=

1000

;

       

Integer

[

]

arr

=

SortTestHelper.

generateRandomArray

(

N,

0

,

100000

)

;

        sort

(

arr

)

;

       

// Print the array

        SortTestHelper.

printArray

(

arr

)

;

   

}

}


Algorithm Principles and Detailed Steps

The implementation of merge sort mainly relies on two core functions:merge_sort(responsible for "divide") and merge(responsible for "conquer").

1. Divide function merge_sort

This function works recursively:

Base case: If the current array's length is less than or equal to 1, it is already ordered, so return directly.

Recursive case:

2. Merge function merge

This is the essence of the algorithm, responsible for merging twoalready orderedsmall arrays into one large ordered array. The process is similar to flipping through two alphabetically sorted address books at the same time and merging them into one.

  1. Create a temporary array temp, and three pointers:i(pointing to the current element of the left array),j(pointing to the current element of the right array),k(pointing to the filling position of the temporary array).
  2. Comparison left[i] and right[j], and replaceSmallerput the element with temp[k], then the corresponding pointer and k move forward one step.
  3. Repeat step 2 until all elements of one array have been placed into the temporary array.
  4. Append all remaining elements of the other array (which are inherently larger than the already placed elements and already ordered) directly in order to the end of the temporary array.
  5. Copy the ordered sequence in the temporary array temp back to the corresponding position in the original array.

Code Implementation and Line-by-Line Analysis

Let's implement merge sort in Python. We will provide a complete, heavily commented version.

Test Data

First, we prepare an unordered list as test data:

Example

Test data: an unordered list of integers

test_array

=

[

38

,

27

,

43

,

3

,

9

,

82

,

10

]

print

(

"Original array:"

,

test_array

)

Complete implementation

Example

def

merge_sort

(

arr

)

:

   

"""
    The main function of merge sort.
    Parameters:
        arr (list): the list to be sorted.
    Returns:
        list: the new sorted list (for clarity, this implementation returns a new list).
    """

   

Base case: if the array length is 0 or 1, it is already sorted

   

if

len

(

arr

)

<=

1

:

       

return

arr

   

1. Divide: find the midpoint and split the array into two halves

    mid

=

len

(

arr

)

//

2

    left_half

=

arr

[

:mid

]

 

the left half

    right_half

=

arr

[

mid:

]

the right half

   

Recursively sort the left and right halves

    left_sorted

=

merge_sort

(

left_half

)

    right_sorted

=

merge_sort

(

right_half

)

   

2. Conquer: merge the two sorted subarrays

   

return

merge

(

left_sorted

,

right_sorted

)

def

merge

(

left

,

right

)

:

   

"""
    Merge two sorted lists.
    Parameters:
        left (list): the first sorted list.
        right (list): the second sorted list.
    Returns:
        list: the merged sorted list.
    """

    sorted_list

=

[

]

 

A temporary list used to hold the merge result

    i

=

j

=

0

       

i and j are pointers for traversing left and right, respectively

   

3. Compare and merge: while both lists still have elements

   

while

i

<

len

(

left

)

and

j

<

len

(

right

)

:

       

if

left

[

i

]

<=

right

[

j

]

:  

Note the use of <= to maintain the stability of the sort

            sorted_list.

append

(

left

[

i

]

)

            i +

=

1

       

else

:

            sorted_list.

append

(

right

[

j

]

)

            j +

=

1

   

4. Handle remaining elements: append all remaining elements from the left or right list to the result

   

   Since left and right are already sorted, the remaining elements are all greater than the elements already merged

    sorted_list.

extend

(

left

[

i:

]

)

    sorted_list.

extend

(

right

[

j:

]

)

   

return

sorted_list

Run the algorithm with test data

sorted_array

=

merge_sort

(

test_array.

copy

(

)

)

 

Use copy to avoid modifying the original array

print

(

"After merge sort:"

,

sorted_array

)

Code execution and output

When you run the code above, you will see the following output:

原始数组: [38, 27, 43, 3, 9, 82, 10]

归并排序后: [3, 9, 10, 27, 38, 43, 82]


Algorithm Complexity Analysis

Understanding the efficiency of an algorithm is crucial. We summarize the performance of merge sort in the table below:

Pointer Complexity Description
Time Complexity O(n log n) This is the most significant advantage of merge sort.log n comes from the number of recursion levels (splitting the array in half),n comes from the fact that each merge operation at every level must traverse all elements. Regardless of the initial state of the data (best, worst, or average case), the time complexity is O(n log n).
Space complexity O(n) The merge process requires extra space equal in size to the original array to store temporary arrays. This is the main drawback of merge sort.
Stability Stable in merge In the function, when left[i] == right[j] , we preferentially take left[i](using the <= comparison), which guarantees that the original relative order of equal elements remains unchanged.
Whether it sorts in place No Requires additional memory space.

More Code Examples