0% found this document useful (0 votes)
47 views

Merge Two Arrays

The document contains C code to merge two integer arrays into a single sorted array. It takes the number of elements in each array as input, stores the element values in the respective arrays, and then uses a while loop to iteratively compare and insert elements from the first array or second array into a result array based on element value. Finally it prints out the merged sorted array.

Uploaded by

akurathikotaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Merge Two Arrays

The document contains C code to merge two integer arrays into a single sorted array. It takes the number of elements in each array as input, stores the element values in the respective arrays, and then uses a while loop to iteratively compare and insert elements from the first array or second array into a result array based on element value. Finally it prints out the merged sorted array.

Uploaded by

akurathikotaiah
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

#include<stdio.

h>
main()
{
int arr1[30], arr2[30], res[60];
int i, j, k, n1, n2;
printf("\nEnter no of elements in 1st
array :");
scanf("%d", &n1);
for (i = 0; i < n1; i++)
{
scanf("%d", &arr1[i]);
}
printf("\nEnter no of elements in 2nd
array :");
scanf("%d", &n2);
for (i = 0; i < n2; i++)
{
scanf("%d", &arr2[i]);
}
i = 0;
j = 0;
k = 0;
// Merging starts
while (i < n1 && j < n2)
{
if (arr1[i] <= arr2[j])
{
res[k] = arr1[i];
i++;
k++;
}
else
{
res[k] = arr2[j];
k++;
j++;
}
}
/* Some elements in array 'arr1' are
still remaining
where as the array 'arr2' is
exhausted */
while (i < n1)
{
res[k] = arr1[i];
i++;
k++;
}
/* Some elements in array 'arr2' are
still remaining
where as the array 'arr1' is
exhausted */
while (j < n2)
{
res[k] = arr2[j];
k++;
j++;
}
//Displaying elements of array 'res'
printf("\nMerged array is :");
for (i = 0; i < n1 + n2; i++)
printf("%d ", res[i]);
getch();
}
Output
============

Enter no of elements in 1st array : 4


11 22 33 44
Enter no of elements in 2nd array : 3
10 40 80
Merged array is : 10 11 22 33 40 44 80

You might also like