java 25 lines · 6 steps

Merging two sorted arrays in Java

Two pointers walk both sorted inputs in lockstep, copying the smaller head each time to build one merged array in linear time.

Explained by highlit
1public class SortedListMerger {
2 
3 public static int[] merge(int[] a, int[] b) {
4 int[] result = new int[a.length + b.length];
5 int i = 0, j = 0, k = 0;
6 
7 while (i < a.length && j < b.length) {
8 if (a[i] <= b[j]) {
9 result[k++] = a[i++];
10 } else {
11 result[k++] = b[j++];
12 }
13 }
14 
15 while (i < a.length) {
16 result[k++] = a[i++];
17 }
18 
19 while (j < b.length) {
20 result[k++] = b[j++];
21 }
22 
23 return result;
24 }
25}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1When both inputs are already sorted, a single linear pass beats re-sorting the combined data.
  2. 2Independent pointers let you consume two sequences at different rates without nested loops.
  3. 3Always handle the leftover tail of whichever input outlasts the other after the main merge ends.

Related explainers

Share this explainer

Here's the card — post it anywhere.

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