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 interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
java
import java.util.ArrayDeque; import java.util.Deque; import java.util.Map;
Evaluating math expressions with two stacks
stacks
parsing
operator-precedence
Intermediate
9 steps
java
@Entity @Table(name = "orders") @SQLDelete(sql = "UPDATE orders SET deleted = true, deleted_at = now() WHERE id = ?") @Where(clause = "deleted = false")
Soft deletes with Hibernate in Spring
soft-delete
jpa
hibernate
Intermediate
9 steps
java
@GetMapping("/files/{id}") public ResponseEntity<StreamingResponseBody> download( @PathVariable String id, @RequestHeader(value = HttpHeaders.RANGE, required = false) String rangeHeader) throws IOException {
HTTP range requests in Spring
http-range
streaming
file-io
Advanced
10 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.