Merge two 1-D array: C Program

0
18

Two 1 dimensional array arry1 and arry2 ,which are sorted in ascending order.Write a program two merge them into 1-D array  arry3 that contain all elements from array arr1 and arr2 in ascending order.

[message_box title=”Program” color=”yellow”]

#include<stdio.h>

#include<conio.h>
void main()
{
int arry1[30], arry2[30], arry3[60];
int i, j, k, n1, n2;
clrscr();

printf(“\nEnter no of elements in 1st array :”);
scanf(“%d”, &n1);
for (i = 0; i < n1; i++) {
scanf(“%d”, &arry1[i]);
}

printf(“\nEnter no of elements in 2nd array :”);
scanf(“%d”, &n2);
for (i = 0; i < n2; i++) {
scanf(“%d”, &arry2[i]);
}

i = 0;
j = 0;
k = 0;

/* Merging starts */
while (i < n1 && j < n2) {
if (arry1[i] <= arry2[j]) {
arry3[k] = arry1[i];
i++;
k++;
}
else
{
arry3[k] = arry2[j];
k++;
j++;
}
}

/* Some elements in array ‘arry1’ are still remaining
where as the array ‘arry2’ is exhausted */

while (i < n1) {
arry3[k] = arry1[i];
i++;
k++;
}

/* Some elements in array ‘arry2’ are still remaining
where as the array ‘arry1’ is exhausted */

while (j < n2) {
arry3[k] = arry2[j];
k++;
j++;
}

//Displaying elements of array ‘arry3’
printf(“\n Resultant merged array is :”);
for (i = 0; i < n1 + n2; i++)
printf(“%d “, arry3[i]);

}

[/message_box]

[/sociallocker-bulk-1]

Leave a Reply

Be the First to Comment!

Notify of
wpDiscuz