go 19 lines · 6 steps

Merging two sorted slices in Go

Two pointers walk two pre-sorted slices at once to produce a single sorted result in linear time.

Explained by highlit
1func MergeSorted(a, b []int) []int {
2 merged := make([]int, 0, len(a)+len(b))
3 i, j := 0, 0
4 
5 for i < len(a) && j < len(b) {
6 if a[i] <= b[j] {
7 merged = append(merged, a[i])
8 i++
9 } else {
10 merged = append(merged, b[j])
11 j++
12 }
13 }
14 
15 merged = append(merged, a[i:]...)
16 merged = append(merged, b[j:]...)
17 
18 return merged
19}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1The merge step of merge sort runs in linear time because each element is visited exactly once.
  2. 2Pre-allocating a slice with a known capacity avoids repeated reallocation as it grows.
  3. 3After one input is exhausted, the remainder of the other is already sorted and can be appended wholesale.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Merging two sorted slices in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code