Merge Two Sorted Arrays in C

How to merge two sorted arrays in the C programming language? We have two sorted arrays and merge them in ascending order. For this, we need to insert each element at the appropriate position.

Example1 of merging of two int arrays in ascending order,
Array1 = { 9, 18, 27, 36, 45 }
Array2 = { 10, 20, 30, 40, 50 }
Then the Result should be,
Merged Array = { 9, 10, 18, 20, 27, 30, 36, 40, 45, 50 }

Example2 of merging of two int arrays in ascending order,
Array1 = {1, 9, 10, 14, 15}
Array2 = {2, 3, 5, 11, 12}
Then the Result should be,
Merged Array = {1, 2, 3, 5, 9, 10, 11, 12, 14, 15}

Steps to merge two sorted arrays in C,
1) Take two arrays, assume src1 and src2
2) Calculate the size of both arrays using sizeof() function, assume n1 and n2
3) Create a new array of a similar data type with the size = n1+n2
4) Compare elements of both arrays and insert the lower element to the new array
5) Merge remaining elements of the first array to the new array
6) Merge remaining elements of the second array to the new array
7) Display the resultant array

#include <stdio.h>
// function to merge two sorted array in 
// ascending order
void mergeSorted(int src1[], int src2[], 
  int newArr[], int n1, int n2)
{
  // variables
  int i = 0, j = 0, k = 0; 

  // merge two sorted arrays into newArr[] 
  while (i < n1 && j < n2) 
  { 
    // compare elements of both arrays
    if (src1[i] <= src2[j]) 
    { 
      newArr[k++] = src1[i++]; 
    } 
    else 
    { 
      newArr[k++] = src2[j++]; 
    } 
  }     
  
  // merg remaining elements 
  // of src1[] (if any) 
  while (i < n1) 
  {
    newArr[k++] = src1[i++]; 
  }

  // merg remaining elements 
  // of src2[] (if any) 
  while (j < n2) 
  {   
    newArr[k++] = src2[j++]; 
  } 
}

// main function
int main()
{
  // array which should be merged
  int src1[] = {9, 18, 27, 36, 45};
  int src2[] = {10, 20, 30, 40, 50};

  // calculate size
  int n1 = sizeof(src1)/sizeof(src1[0]);
  int n2 = sizeof(src2)/sizeof(src2[0]);
      
  // create new array
  int newArr[n1+n2];

  mergeSorted(src1, src2, newArr, n1, n2);

  // display newArrultant array
  printf("New array = ");
  for (int i = 0; i < n1+n2; i++) {
    printf("%d ",newArr[i]);
  }

  return 0;
}

Output:-

New array = 9 10 18 20 27 30 36 40 45 50

In this C program, we have directly initialized the value for the variable, but you can take the input from end-user & perform operation.

Also See:-

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Leave a Reply