Merge Two Sorted Slices
Combine two ascending slices into one ordered result with a two index merge, allocating once and avoiding a resort.
Code
package main
import "fmt"
// 双指针归并:两输入各自有序,一次线性扫描得到整体有序
func mergeSorted(a, b []int) []int {
merged := make([]int, 0, len(a)+len(b))
i, j := 0, 0
for i < len(a) && j < len(b) {
if a[i] <= b[j] {
merged = append(merged, a[i])
i++
} else {
merged = append(merged, b[j])
j++
}
}
// 剩余尾部直接追加
merged = append(merged, a[i:]...)
merged = append(merged, b[j:]...)
return merged
}
func main() {
left := []int{1, 4, 9, 12}
right := []int{2, 3, 10}
fmt.Println(mergeSorted(left, right))
fmt.Println(mergeSorted(left, nil))
}How it works
Merge Two Sorted Slices comes down to the functions mergeSorted and main.
A single loop drives the file — for i < len(a) && j < len(b).
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: func mergeSorted(a, b []int) []int
Running the file executes main, which drives mergeSorted in order.
Key statements
func main() {
left := []int{1, 4, 9, 12}
right := []int{2, 3, 10}
fmt.Println(mergeSorted(left, right))
fmt.Println(mergeSorted(left, nil))
}
merged := make([]int, 0, len(a)+len(b))
merged = append(merged, a[i:]...)
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Merge Two Sorted Slices?
- This is a complete program, not a library excerpt — execution starts at the top.
Report a problem with this exampleOpens a pre-filled issue on GitHub.