- How to merge two arrays into a single array
- How to combine elements from both arrays
- How to merge sorted arrays in order
- Step-by-step explanation of the program
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to merge two arrays into a single array.
Merging two arrays is a common operation in programming. It is used in many real-world applications, such as:
- Combining two lists of data (like merging two class lists)
- Merging sorted arrays (merge sort algorithm)
- Combining results from multiple sources
- Database query result merging
💡 Key Point: To merge two arrays, we create a third array with a size equal to the sum of the sizes of the two arrays, then copy all elements from both arrays into it.
C Program to Merge Two Arrays
#include <stdio.h>
int main() {
int n1, n2, i;
// ====== FIRST ARRAY ======
printf("Enter the number of elements in first array: ");
scanf("%d", &n1);
int arr1[n1];
printf("Enter %d elements:\n", n1);
for(i = 0; i < n1; i++) {
scanf("%d", &arr1[i]);
}
// ====== SECOND ARRAY ======
printf("\nEnter the number of elements in second array: ");
scanf("%d", &n2);
int arr2[n2];
printf("Enter %d elements:\n", n2);
for(i = 0; i < n2; i++) {
scanf("%d", &arr2[i]);
}
// ====== MERGE ======
int merged[n1 + n2];
// Copy elements from first array
for(i = 0; i < n1; i++) {
merged[i] = arr1[i];
}
// Copy elements from second array
for(i = 0; i < n2; i++) {
merged[n1 + i] = arr2[i];
}
// ====== DISPLAY ======
printf("\nFirst array: ");
for(i = 0; i < n1; i++) {
printf("%d ", arr1[i]);
}
printf("\nSecond array: ");
for(i = 0; i < n2; i++) {
printf("%d ", arr2[i]);
}
printf("\nMerged array: ");
for(i = 0; i < n1 + n2; i++) {
printf("%d ", merged[i]);
}
printf("\n");
return 0;
}
Sample Output
Enter the number of elements in first array: 3 Enter 3 elements: 10 20 30 Enter the number of elements in second array: 4 Enter 4 elements: 40 50 60 70 First array: 10 20 30 Second array: 40 50 60 70 Merged array: 10 20 30 40 50 60 70
Another Example:
Enter the number of elements in first array: 2 Enter 2 elements: 5 15 Enter the number of elements in second array: 3 Enter 3 elements: 25 35 45 First array: 5 15 Second array: 25 35 45 Merged array: 5 15 25 35 45
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Declare Variables:
int n1, n2;— sizes of the two arraysint i;— loop counter
- Read First Array: Reads the size and elements of the first array.
- Read Second Array: Reads the size and elements of the second array.
- Merge the Arrays:
int merged[n1 + n2];— creates a merged array with total size- First loop copies all elements from
arr1intomerged - Second loop copies all elements from
arr2intomergedstarting at indexn1
- Display Results: Prints all three arrays.
- Return:
return 0;indicates successful program execution.
📝 Note: The merged array's size is n1 + n2. Make sure both source arrays are large enough to hold all elements.
Method 2: Merging Sorted Arrays (Merge Sort Style)
When both arrays are already sorted, we can merge them efficiently in O(n1 + n2) time using a two-pointer approach. This is the core of the merge sort algorithm.
#include <stdio.h>
int main() {
int n1, n2, i, j, k;
// Read first sorted array
printf("Enter number of elements in first sorted array: ");
scanf("%d", &n1);
int arr1[n1];
printf("Enter %d sorted elements:\n", n1);
for(i = 0; i < n1; i++) {
scanf("%d", &arr1[i]);
}
// Read second sorted array
printf("\nEnter number of elements in second sorted array: ");
scanf("%d", &n2);
int arr2[n2];
printf("Enter %d sorted elements:\n", n2);
for(i = 0; i < n2; i++) {
scanf("%d", &arr2[i]);
}
// Merge sorted arrays
int merged[n1 + n2];
i = 0; j = 0; k = 0;
while(i < n1 && j < n2) {
if(arr1[i] < arr2[j]) {
merged[k] = arr1[i];
i++;
} else {
merged[k] = arr2[j];
j++;
}
k++;
}
// Copy remaining elements from first array
while(i < n1) {
merged[k] = arr1[i];
i++;
k++;
}
// Copy remaining elements from second array
while(j < n2) {
merged[k] = arr2[j];
j++;
k++;
}
// Display merged array
printf("\nMerged sorted array: ");
for(i = 0; i < n1 + n2; i++) {
printf("%d ", merged[i]);
}
printf("\n");
return 0;
}
Sample Output:
Enter number of elements in first sorted array: 4 Enter 4 sorted elements: 10 20 30 40 Enter number of elements in second sorted array: 3 Enter 3 sorted elements: 15 25 35 Merged sorted array: 10 15 20 25 30 35 40
How Sorted Array Merge Works
- Two Pointers:
ipoints to arr1,jpoints to arr2 - Compare: Compare
arr1[i]andarr2[j], add the smaller one to merged array - Advance: Move the pointer of the array from which the element was taken
- Remaining: After one array is exhausted, copy all remaining elements from the other array
- Time Complexity: O(n1 + n2)
Algorithm to Merge Two Arrays
- Start
- Read size and elements of first array (arr1)
- Read size and elements of second array (arr2)
- Create merged array of size n1 + n2
- For
i = 0ton1-1:- Set
merged[i] = arr1[i]
- Set
- For
j = 0ton2-1:- Set
merged[n1 + j] = arr2[j]
- Set
- Print the merged array
- End
💻 Practice Exercise
Challenge 1: Merge two arrays and then remove duplicate elements from the merged array.
Challenge 2: Merge two arrays in alternating order (arr1[0], arr2[0], arr1[1], arr2[1], ...).
🔍 Click to Show Solution for Challenge 2
#include <stdio.h>
int main() {
int n1, n2, i, j = 0;
printf("Enter number of elements in first array: ");
scanf("%d", &n1);
int arr1[n1];
printf("Enter %d elements:\n", n1);
for(i = 0; i < n1; i++) {
scanf("%d", &arr1[i]);
}
printf("Enter number of elements in second array: ");
scanf("%d", &n2);
int arr2[n2];
printf("Enter %d elements:\n", n2);
for(i = 0; i < n2; i++) {
scanf("%d", &arr2[i]);
}
// Alternate merge
int merged[n1 + n2];
int k = 0;
int max_size = n1 > n2 ? n1 : n2;
for(i = 0; i < max_size; i++) {
if(i < n1) {
merged[k] = arr1[i];
k++;
}
if(i < n2) {
merged[k] = arr2[i];
k++;
}
}
printf("\nAlternate merged array: ");
for(i = 0; i < n1 + n2; i++) {
printf("%d ", merged[i]);
}
printf("\n");
return 0;
}
/* Sample Output:
Enter number of elements in first array: 3
Enter 3 elements:
10 20 30
Enter number of elements in second array: 4
Enter 4 elements:
40 50 60 70
Alternate merged array: 10 40 20 50 30 60 70
*/
Frequently Asked Questions
1. How do you merge two arrays in C?
Create a third array with size equal to the sum of the two arrays. Copy all elements from the first array, then copy all elements from the second array into the third array.
2. What is the time complexity of merging two arrays?
The time complexity is O(n1 + n2), where n1 and n2 are the sizes of the two arrays. For sorted arrays, it's also O(n1 + n2).
3. Can I merge two arrays of different data types?
No, arrays must be of the same data type to be merged directly. You would need to create a structure or union to store different types.
4. How do I merge sorted arrays without extra space?
You need extra space to store the merged result. However, you can merge into an existing array if it's large enough using the memcpy function.
5. What is the difference between concatenation and merging?
Concatenation simply joins two arrays one after another. Merging typically refers to combining sorted arrays while maintaining the sorted order.
💡 Tip: When merging sorted arrays, use the two-pointer method for better performance. This is the same algorithm used in merge sort.