C program to Merge Two Arrays after Sorting

Merging is one of the basic operation which is applied to Arrays, in this tutorial, we will learn how to merge two arrays into a single array.

To merge the arrays we first need to sort the two arrays which are going to be merged and the merging is carried out in such a way that the resultant array is sorted.

C program to merge two arrays after sorting

Let us take two sorted arrays

a[] = {2, 4, 6, 8}

b[] = {1, 3, 5, 7}

c[] = {}

Then we will carry out the merging at index = 0 and will do the following actions

Initial stage

if(a[0] < b[0]) c[0] = a[0]

else c[0] = b[0] c[] = {1}

Second stage

if(a[0] < b[1]) c[1] = a[0] c[] = {1, 2}

else c[1] = b[1]

Third stage

if(a[1] < b[1]) c[2] = a[1]

else c[2] = b[1] c[] = {1, 2, 3}

and we can do the further merging as shown above.

First, we will make a sort function to sort the two arrays which are going to be merged.

void sort(int arr[],int size){ int i,j,temp; for(i=0;i<size;i++){ for(j=i;j<size;j++){ if(arr[i]>arr[j]){ temp = arr[i]; arr[i] = arr[j]; arr[j] =  temp; } } } }

Now we will make C program to merge two arrays, see the below code snippet

#include<stdio.h> void sort(int arr[],int size){  // sorting function int i,j,temp; for(i=0;i<size;i++){ for(j=i;j<size;j++){ if(arr[i]>arr[j]){ temp = arr[i]; arr[i] = arr[j]; arr[j] =  temp; } } } } int main(){ int a[10],b[10],c[10]; int n,i,k=0,j=0; printf("Enter the size of the array:"); scanf("\%d",&n); for(i=0;i<n;i++){ printf("Enter the element of array A at index \%d:",i); //input array A scanf("\%d",&a[i]); } sort(a,n); for(i=0;i<n;i++){ printf("Enter the element of array B at index \%d:",i);  //Input array B scanf("\%d",&b[i]); } sort(b,n); for(i=0;i<(n+n);i++){   // merging the two arrays if(a[k]<b[j]){ c[i] = a[k]; k++; } else{ c[i] = b[j]; j++; } } printf("Merged Array :"); for(i=0;i<(n+n);i++){ printf("c -> \%d ",c[i]); } return 0; }

Output of the above code:

C program to merge two arrays

Thanks for reading

Tweet your queries and feedback to @PsychoCodes or leave a message on our Facebook page. You can also comment your questions below.

Also, don’t forget to subscribe to our Newsletter.

If you like this article, then please share it and help us grow.


C program to generate all combinations of N-Bit Binary String
10 July 2018

Data Autosave System using PHP, MySQL and AJAX
06 July 2018

Macros in C with examples C Tutorials
30 January 2018

Armstrong Number program in C and C++
29 January 2018

Creating a Fixed Header Navigation Bar with on scroll effect
28 January 2018

C program to find Modular Multiplicative Inverse of two Relatively Prime Numbers
25 January 2018

Понравилась статья? Поделиться с друзьями:
Добавить комментарий