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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1When both inputs are already sorted, a single linear pass beats re-sorting the combined data.
- 2Independent pointers let you consume two sequences at different rates without nested loops.
- 3Always handle the leftover tail of whichever input outlasts the other after the main merge ends.
Related explainers
java
public class ThumbnailProcessor { private static final int MAX_CONCURRENCY = 4;
Bounded parallel thumbnail rendering in Java
concurrency
thread-pool
futures
Intermediate
7 steps
java
import java.util.ArrayDeque; import java.util.Deque; public final class RollingAverage {
A rolling average over a sliding window
sliding-window
running-sum
deque
Intermediate
7 steps
java
@Target({ElementType.FIELD, ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = StrongPasswordValidator.class) @Documented
Building a custom @StrongPassword validator in Spring
bean-validation
annotations
regex
Intermediate
7 steps
java
@Component public class JwtAuthenticationFilter extends OncePerRequestFilter { private final JwtTokenProvider tokenProvider;
How a JWT auth filter works in Spring
authentication
jwt
servlet-filter
Intermediate
8 steps
java
@Entity @Table(name = "accounts") public class Account {
Optimistic locking with @Version in Spring
optimistic-locking
jpa
concurrency
Advanced
7 steps
java
import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.math.BigInteger;
A thread-safe memoized factorial cache
memoization
thread-safety
caching
Intermediate
6 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-arrays-in-java-explained-java-9735/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.