Skip to content

Array Merge

Merge two sorted arrays into a single sorted array.

Array merge combines two sorted arrays into one sorted sequence. It is a fundamental operation in merge sort and external sorting.

You use it when two ordered sequences must be combined while preserving order.

Problem

Given two sorted arrays AA and BB of lengths nn and mm, produce a sorted array CC containing all elements:

C=merge(A,B) C = \text{merge}(A, B)

Algorithm

Use two pointers and repeatedly select the smaller element.

merge(A, B):
    i = 0
    j = 0
    C = empty array

    while i < length(A) and j < length(B):
        if A[i] <= B[j]:
            append A[i] to C
            i += 1
        else:
            append B[j] to C
            j += 1

    while i < length(A):
        append A[i] to C
        i += 1

    while j < length(B):
        append B[j] to C
        j += 1

    return C

Example

Let

A=[1,4,7] A = [1, 4, 7]

and

B=[2,3,6] B = [2, 3, 6]
stepijchosenC
1001[1]
2102[1, 2]
3113[1, 2, 3]
4124[1, 2, 3, 4]
5226[1, 2, 3, 4, 6]
6237[1, 2, 3, 4, 6, 7]

Result:

[1,2,3,4,6,7] [1, 2, 3, 4, 6, 7]

Correctness

At each step, the algorithm selects the smallest remaining element from the heads of AA and BB. Since both arrays are sorted, this element is the smallest among all remaining elements. Appending it preserves sorted order.

After one array is exhausted, the remaining elements of the other array are already in sorted order and can be appended directly.

Complexity

operationtime
mergeO(n+m)O(n + m)

Space usage:

O(n+m) O(n + m)

When to Use

Array merge is appropriate when:

  • combining sorted sequences
  • implementing merge sort
  • merging results from multiple sources
  • streaming sorted data

It is less suitable when:

  • inputs are unsorted
  • in-place merging is required with strict memory constraints

Implementation

def merge(a, b):
    i, j = 0, 0
    c = []

    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            c.append(a[i])
            i += 1
        else:
            c.append(b[j])
            j += 1

    c.extend(a[i:])
    c.extend(b[j:])
    return c
func Merge(a, b []int) []int {
    i, j := 0, 0
    c := make([]int, 0, len(a)+len(b))

    for i < len(a) && j < len(b) {
        if a[i] <= b[j] {
            c = append(c, a[i])
            i++
        } else {
            c = append(c, b[j])
            j++
        }
    }

    c = append(c, a[i:]...)
    c = append(c, b[j:]...)
    return c
}