Unit 4 Cycle 2 Day 20: Array: Merge Two Sorted Arrays

Unit 4 Advanced (Cycle 2) Day 20 of 28 Advanced

Array: Merge Two Sorted Arrays

Section 4.3 — Common Array Algorithms

Key Concept

Merging two sorted arrays into a single sorted array uses the two-pointer technique. Maintain an index for each input array and one for the output. Compare the elements at both input indices, copy the smaller one to the output, and advance that input's index. When one input is exhausted, copy the remaining elements from the other. The result is a sorted array of length equal to the sum of the inputs. The AP exam traces this algorithm and asks about the final state or the number of comparisons needed.

Consider the following merge algorithm.

int[] a = {1, 3, 5}; int[] b = {2, 4, 6}; int[] m = new int[6]; int ai = 0, bi = 0, mi = 0; while (ai < a.length && bi < b.length) { if (a[ai] <= b[bi]) m[mi++] = a[ai++]; else m[mi++] = b[bi++]; } while (ai < a.length) m[mi++] = a[ai++]; while (bi < b.length) m[mi++] = b[bi++]; System.out.println(m[3]);

What is printed?

Answer: (B) 4

Merge: 1,2,3,4,5,6. m[3]=4.

Why Not the Others?

(A) 3 is at m[2].

(C) 5 is at m[4].

(D) 2 is at m[1].

Common Mistake

Merge: compare front elements of both sorted arrays, take smaller. Two-pointer technique.

AP Exam Tip

The merge algorithm combines two sorted arrays in O(n) time. Know the two-pointer pattern.

Review this topic: Section 4.3 — Common Array Algorithms • Unit 4 Study Guide
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.