Unit 4 Cycle 2 Day 20: Array: Merge Two Sorted Arrays
Share
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.
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.