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 and of lengths and , produce a sorted array containing all elements:
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 CExample
Let
and
| step | i | j | chosen | C |
|---|---|---|---|---|
| 1 | 0 | 0 | 1 | [1] |
| 2 | 1 | 0 | 2 | [1, 2] |
| 3 | 1 | 1 | 3 | [1, 2, 3] |
| 4 | 1 | 2 | 4 | [1, 2, 3, 4] |
| 5 | 2 | 2 | 6 | [1, 2, 3, 4, 6] |
| 6 | 2 | 3 | 7 | [1, 2, 3, 4, 6, 7] |
Result:
Correctness
At each step, the algorithm selects the smallest remaining element from the heads of and . 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
| operation | time |
|---|---|
| merge |
Space usage:
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 cfunc 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
}