Merging two sorted arrays
What you'll learn: How to combine two already-sorted arrays into a single, larger sorted array efficiently using the "zipper" technique.
The Zipper Logic
Imagine you have two stacks of numbered cards on a table. Both stacks are already sorted from lowest to highest. You want to merge them into one big sorted pile.
You wouldn't just throw them together and re-sort the whole mess—that’s extra work! Instead, you look at the top card of each stack. You take the smaller one, place it in your new pile, and move to the next card in that stack. You repeat this until one stack is empty, then you simply move the remaining cards from the other stack to the end. This is exactly how we merge two sorted arrays in C.
Implementation in C
To do this, we need three "trackers" (indices): one for Array A, one for Array B, and one for our new Destination Array.
#include <stdio.h>
void merge(int arr1[], int size1, int arr2[], int size2, int result[]) {
int i = 0; // Tracker for arr1
int j = 0; // Tracker for arr2
int k = 0; // Tracker for result
// While there are elements in both arrays
while (i < size1 && j < size2) {
if (arr1[i] < arr2[j]) {
result[k++] = arr1[i++];
} else {
result[k++] = arr2[j++];
}
}
// Copy remaining elements of arr1, if any
while (i < size1) {
result[k++] = arr1[i++];
}
// Copy remaining elements of arr2, if any
while (j < size2) {
result[k++] = arr2[j++];
}
}
Why this works
We use a single while loop to compare the current elements of both arrays. By always picking the smaller value, we ensure the result array is built in order.
Notice the two extra while loops at the end. When one array "runs out" of numbers, the other array usually still has numbers left. Since the input arrays were already sorted, we know those remaining numbers are larger than everything we’ve picked so far, so we can just "dump" them into the end of the result.
This method is highly efficient because we only look at each number exactly once. This logic is the foundation of more advanced algorithms, like the Merge Sort.
Key takeaway
To merge sorted arrays, compare the front-most elements of both and move the smaller one into the new array until all elements are exhausted.