We have two arrays A and B (of respective dimensions N and M). Merge the elements of A and B into a third FUS array sorted in ascending order.
Method: we will loop over each array and insert the element in a sorted way in the FUS array.
Difficulty level
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define SIZE 100
void main()
{
int A[SIZE], B[SIZE], FUS[2 * SIZE];
int N, M;
int i, j, k;
do {
printf("Enter N: ");
scanf("%d", &N);
} while (N <= 0 || N > SIZE);
printf("Enter A: ");
for (i = 0;i < N;i++)
scanf("%d", &A[i]);
do {
printf("Enter M: ");
scanf("%d", &M);
} while (M <= 0 || M > SIZE);
printf("Enter B: ");
for (i = 0;i < M;i++)
scanf("%d", &B[i]);
// loop over A
k = 0;
for (i = 0;i < N;i++)
{
if (k == 0)
FUS[k++] = A[i];
else
{
j = k - 1;
while (A[i] < FUS[j] && j>=0)
{
FUS[j+1] = FUS[j];
j--;
}
FUS[j + 1] = A[i];
k++;
}
}
// loop over B
for (i = 0;i < M;i++)
{
j = k - 1;
while (B[i] < FUS[j] && j >= 0)
{
FUS[j + 1] = FUS[j];
j--;
}
FUS[j + 1] = B[i];
k++;
}
printf("\n\n** FUS ** \n");
for (i = 0;i < k;i++)
printf("%4d", FUS[i]);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Binary tree rotations