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
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
java
public final class EncodingDetector { public enum Encoding { UTF_8, UTF_16LE, UTF_16BE, UTF_32LE, UTF_32BE, ASCII, UNKNOWN
Detecting text encoding from raw bytes in Java
byte-manipulation
encoding-detection
bitwise-operations
Intermediate
8 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.