C Program to Merge Two Sorted Array Elements

«
»

Merging two arrays in c is similar to Concatenating or combining two arrays into a single array. For example, if the first array has four elements and the second array has five elements, the resulting array has nine elements.

Example:
First Array = [1, 2, 3, 4, 5]
Second Array = [6, 7, 8, 9, 10]

Merged Array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Problem Description

Write a C program to merge two sorted array elements into a single array.

Problem Solution

1. Create two arrays of some fixed size and define their elements in sorted fashion.
2. Take two variables i and j, which will be at the 0th position of these two arrays.
3. Elements will be compared one by one using i and j in for loop, and whichever element is smaller than the other, that element will get inserted to final array and the position(either i or j) will move by one, whereas the other array’s track position will remain in that same place.
4. Above work will be done till we reach the end of either array. After that, one of the array whose elements are still to be added, its elements will get straightaway added to the final array.

There are several ways to merge two sorted array elements into a single array in C language. Let’s take a detailed look at all the approaches to merge the elements of 2 sorted array.

Note: Join free Sanfoundry classes at Telegram or Youtube
advertisement
advertisement

Method 1: Merge Two Sorted Arrays in C using For Loop (Naive Approach)

In this approach, we will use a for loop to iterate through the array and merge the two arrays.

Example:
First Array = [12, 18, 23]
Second Array = [13, 19, 27]

Merged Array = [12, 13, 18, 19, 23, 27]

Program/Source Code

Here is source code of the C Program to merge two sorted arrays using for loop. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

  1. /*
  2.  * C Program to merge two sorted arrays using for loop
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. int main(void)
  9. {
  10.     int i, n, j, k;
  11.     printf("Enter the size of the first array: ");
  12.     scanf("%d", &n);
  13.     int arr1[n];
  14.     printf("Enter the elements of the first array: \n");
  15.     for (i = 0; i < n; i++)
  16.     {
  17.         scanf("%d", &arr1[i]);
  18.     }
  19.     printf("Enter the size of the second array: ");
  20.     scanf("%d", &k);
  21.     int arr2[k];
  22.     printf("Enter the elements of the second array: \n");
  23.     for (j = 0; j < k; j++)
  24.     {
  25.         scanf("%d", &arr2[j]);
  26.     }
  27.     int arr3[n + k];
  28.     i = j = 0;
  29.     int in;
  30.     for (in = 0; in < n + k; in ++)
  31.     {
  32.         if (i < n && j < k)
  33.         {
  34.             if (arr1[i] < arr2[j])
  35.             {
  36.                 arr3[in] = arr1[i];
  37.                 i++;
  38.             }
  39.             else
  40.             {
  41.                 arr3[in] = arr2[j];
  42.                 j++;
  43.             }
  44.         }
  45.         else if (i < n)
  46.         {
  47.             arr3[in] = arr1[i];
  48.             i++;
  49.         }
  50.         else
  51.         {
  52.             arr3[in] = arr2[j];
  53.             j++;
  54.         }
  55.     }
  56.     printf("The merged array is: \n");
  57.     for (in = 0; in < n + k; in++)
  58.     {
  59.         printf("%d ", arr3[in]);
  60.     }
  61.     printf("\n");
  62.     return 0;
  63. }
Program Explanation

1. The program starts with the declaration of two arrays of integers.
2. The first and the second array are initialized with the size of the array.
3. The elements of the first and the second array are then entered by the user.
4. A loop is used to iterate through the array and merge the two arrays.
5. Print the merged array.

Time Complexity: O(n + k)
The time complexity of this algorithm is O(n + k), where n is the size of the first array and k is the size of the second array. This simplifies to O(n) as the loop is executed only once.

Space Complexity: O(n + k)
The space complexity of this algorithm is O(n + k), where n is the size of the first array and k is the size of the second array.

Runtime Test Cases
advertisement

The runtime output of the C program is shown below, where the size of the first array is “3” and the items are 12, 18, and 23. The second array’s size is “3” and the items are 13, 19, and 27. It then combines both array elements and displays it.

Enter the size of the first array: 3
Enter the elements of the first array: 
12
18
23
Enter the size of the second array: 3
Enter the elements of the second array: 
13
19
27
The merged array is: 
12 13 18 19 23 27

Method 2: Merge Two Sorted Arrays in C using While Loop

In this approach, we will use a while loop to iterate through the array and merge the two arrays.

Example:
First Array = [12, 18, 40, 60]
Second Array = [47, 56, 89, 90]

advertisement

Merged Array = [12, 18, 40, 47, 56, 60, 89, 90]

Program/Source Code

Here is source code of the C Program to merge two sorted arrays using while loop. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

  1. /*
  2.  * C Program to merge two sorted arrays using while loop
  3.  */
  4.  
  5. #include <stdio.h>
  6. void main()
  7. {
  8.     int array1[50], array2[50], array3[100], m, n, i, j, k = 0;
  9.     printf("\n Enter size of array Array 1: ");
  10.     scanf("%d", &m);
  11.  
  12.     printf("\n Enter sorted elements of array 1: \n");
  13.     for (i = 0; i < m; i++) 
  14.     {
  15.         scanf("%d", &array1[i]);
  16.     }
  17.  
  18.     printf("\n Enter size of array 2: ");
  19.     scanf("%d", &n);
  20.  
  21.     printf("\n Enter sorted elements of array 2: \n");
  22.     for (i = 0; i < n; i++) 
  23.     {
  24.         scanf("%d", &array2[i]);
  25.     }
  26.  
  27.     i = 0;
  28.     j = 0;
  29.  
  30.     while (i < m && j < n) 
  31.     {
  32.         if (array1[i] < array2[j]) 
  33.         {
  34.             array3[k] = array1[i];
  35.             i++;
  36.         }
  37.         else 
  38.         {
  39.             array3[k] = array2[j];
  40.             j++;
  41.         }
  42.         k++;
  43.     }
  44.  
  45.     if (i >= m) 
  46.     {
  47.         while (j < n) 
  48.         {
  49.             array3[k] = array2[j];
  50.             j++;
  51.             k++;
  52.         }
  53.     }
  54.  
  55.     if (j >= n) 
  56.     {
  57.         while (i < m)
  58.         {
  59.             array3[k] = array1[i];
  60.             i++;
  61.             k++;
  62.         }
  63.     }
  64.  
  65.     printf("\n After merging: \n");
  66.     for (i = 0; i < m + n; i++) 
  67.     {
  68.         printf("\n%d", array3[i]);
  69.     }
  70. }
Program Explanation

1. Declare 2 1D arrays of some fixed size, then take size of the arrays from user and define all the elements of the array according to the size in sorted fashion.
2. Take two variables, i and j as iterators which will track the position of elements in arrays.
3. Running a while loop till we reach the end of either array, the element at ith and jth position of two arrays are compared.
4. The smaller element gets inserted into final array (third array, whose size is the sum of the size of these two arrays) and the track position gets incremented by 1.
5. This process continues, till we reach the end of either array.
6. After finishing the loop above, one of the array’s tracker(i.e either i or j) will not be at the last position of the corresponding array, in that case we will have to add all the remaining elements of that array to the final array as it is one by one.

Time Complexity: O(n + k)
The time complexity of this algorithm is O(n + k), where n is the size of the first array and k is the size of the second array. This simplifies to O(n) as the loop is executed only once.

Space Complexity: O(n + k)
The space complexity of this algorithm is O(n + k), where n is the size of the first array and k is the size of the second array.

Runtime Test Cases

The runtime output of the C program to merge two sorted arrays is shown below, where the size of the first array is “4” and the elements are 12, 18, 40, and 60. The second array’s size is “4” and the elements are 47, 56, 89 and 90. It then combines both array elements and displays it.

Enter size of array Array 1: 4
Enter sorted elements of array 1:
12
18
40
60
Enter size of array 2: 4
 
Enter sorted elements of array 2:
47
56
89
90
After merging:
12
18
40
47
56
60
89
90

Method 3: Merge Two Sorted Arrays in C using Function

In this approach, we will use functions to merge the two arrays.

Example:
First Array = [12, 56, 99]
Second Array = [15, 60]

Merged Array = [12, 15, 56, 60, 99]

Program/Source Code

Here is source code of the C Program to merge two sorted arrays using function. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

  1. /*
  2.  * C Program to merge two sorted arrays using function
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. void init(int *arr, int n)
  9. {
  10.     int i;
  11.     for (i = 0; i < n; i++)
  12.     {
  13.         printf("%d ", i);
  14.         scanf("%d", &arr[i]);
  15.     }
  16. }
  17.  
  18. void print_array(int *arr, int n)
  19. {
  20.     int i;
  21.     printf("[ ");
  22.     for (i = 0; i < n; i++)
  23.     {
  24.         printf("%d ", arr[i]);
  25.     }
  26.     printf("]\n");
  27. }
  28.  
  29. void merge(int *arr1, int *arr2, int *arr3, int n, int k)
  30. {
  31.     int i = 0, j = 0, in = 0;
  32.     while (i < n && j < k)
  33.     {
  34.         if (arr1[i] < arr2[j])
  35.         {
  36.             arr3[in] = arr1[i];
  37.             i++;
  38.         }
  39.         else
  40.         {
  41.             arr3[in] = arr2[j];
  42.             j++;
  43.         }
  44.         in++;
  45.     }
  46.     while (i < n)
  47.     {
  48.         arr3[in] = arr1[i];
  49.         i++;
  50.         in++;
  51.     }
  52.     while (j < k)
  53.     {
  54.         arr3[in] = arr2[j];
  55.         j++;
  56.         in++;
  57.     }
  58. }
  59.  
  60. int main(void)
  61. {
  62.     int i, n, j, k;
  63.     printf("Enter the size of the first array: ");
  64.     scanf("%d", &n);
  65.     int arr1[n];
  66.     printf("Enter the elements of the first array: \n");
  67.     init(arr1, n);
  68.     printf("Enter the size of the second array: ");
  69.     scanf("%d", &k);
  70.     int arr2[k];
  71.     printf("Enter the elements of the second array: \n");
  72.     init(arr2, k);
  73.     int arr3[n + k];
  74.     merge(arr1, arr2, arr3, n, k);
  75.     printf("The merged array is: \n");
  76.     print_array(arr3, n + k);
  77.     return 0;
  78. }
Program Explanation

1. The program asks the user to enter the size of the first and the second array.
2. The elements of the first and the second array are then entered by the user.
3. The arrays are then merged using the merge_arrays function.
4. memcpy to append the first array to the second array.
5. Use separate functions for printing array, merging the arrays and initializing the arrays.
6. The merged array is then printed.
7. The memory is allocated using malloc.

Space Complexity: O(n + k)
The space complexity of this algorithm is O(n + k), where n is the size of the first array and k is the size of the second array.

Time Complexity: O(N)
The time complexity of this algorithm is O(N), where n is the size of the arrays.

Runtime Test Cases

The runtime output of the C program to merge two sorted arrays is shown below, where the size of the first array is “3” and the elements are 12, 56, and 99. The second array’s size is “2” and the elements are 15 and 60. It then combines both array elements and displays it.

Enter the size of the first array: 3
Enter the elements of the first array: 
12
56
99
Enter the size of the second array: 2
Enter the elements of the second array: 
15
60
The merged array is: 
[ 12 15 56 60 99 ]

Method 4: Merge Two Sorted Arrays in C using Pointers

In this approach, we will use pointers to merge the two arrays.

Program/Source Code

Here is source code of the C Program to merge two sorted arrays using pointers. The program is successfully compiled and tested using Turbo C compiler in windows environment. The program output is also shown below.

  1. /*
  2.  * C Program to merge two sorted arrays using pointers
  3.  */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. int main(void)
  9. {
  10.     int i, n, j, k;
  11.     printf("Enter the size of the first array: ");
  12.     scanf("%d", &n);
  13.     int arr1[n];
  14.     printf("Enter the elements of the first array: \n");
  15.     for (i = 0; i < n; i++)
  16.     {
  17.         scanf("%d", &arr1[i]);
  18.     }
  19.     printf("Enter the size of the second array: ");
  20.     scanf("%d", &k);
  21.     int arr2[k];
  22.     printf("Enter the elements of the second array: \n");
  23.     for (j = 0; j < k; j++)
  24.     {
  25.         scanf("%d", &arr2[j]);
  26.     }
  27.     int *arr3 = (int *)malloc((n + k) * sizeof(int));
  28.     i = j = 0;
  29.     int in;
  30.     for (in = 0; in < n + k; in ++)
  31.     {
  32.         if (i < n && j < k)
  33.         {
  34.             if (arr1[i] < arr2[j])
  35.             {
  36.                 arr3[in] = arr1[i];
  37.                 i++;
  38.             }
  39.             else
  40.             {
  41.                 arr3[in] = arr2[j];
  42.                 j++;
  43.             }
  44.         }
  45.         else if (i < n)
  46.         {
  47.             arr3[in] = arr1[i];
  48.             i++;
  49.         }
  50.         else
  51.         {
  52.             arr3[in] = arr2[j];
  53.             j++;
  54.         }
  55.     }
  56.     printf("The merged array is: \n");
  57.     for (in = 0; in < n + k; in++)
  58.     {
  59.         printf("%d ", arr3[in]);
  60.     }
  61.     printf("\n");
  62.     return 0;
  63. }
Program Explanation

1. The program asks the user to enter the size of the first and the second array.
2. The elements of the first and the second array are then entered by the user.
3. A loop is then used to iterate through the array and merge the two arrays.
4. The merged array is then printed.

Space Complexity: O(n + k)
The space complexity of this algorithm is O(n + k), where n is the size of the first array and k is the size of the second array.

Time Complexity: O(N)
The time complexity of this algorithm is O(N), where n is the size of the arrays.

Runtime Test Cases

The runtime output of the C program to merge two sorted arrays is shown below, where the size of the first array is “4” and the elements are 5, 9, 15 and 33. The second array’s size is “5” and the elements are 1, 14, 24, 29, and 37. It then combines both array elements and displays it.

Enter the size of the first array: 4
Enter the elements of the first array: 
5
9
15
33
Enter the size of the second array: 5
Enter the elements of the second array: 
1
14
24
29
37
The merged array is: 
1 5 9 14 15 24 29 33 37

To practice programs on every topic in C, please visit “Programming Examples in C”, “Data Structures in C” and “Algorithms in C”.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.