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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1The merge step of merge sort runs in linear time because each element is visited exactly once.
- 2Pre-allocating a slice with a known capacity avoids repeated reallocation as it grows.
- 3After one input is exhausted, the remainder of the other is already sorted and can be appended wholesale.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
go
package httputil import ( "net"
Safely extracting the real client IP in Go
security
http
ip-spoofing
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/merging-two-sorted-slices-in-go-explained-go-7665/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.