We have two arrays A and B (of respective dimensions N and M), sorted in ascending order. Merge the elements of A and B into a third FUS array sorted in ascending order.

 

Method: Use three indexes i, j and k. Compare A[i] and B[j]; replace FUS[k] with the smaller of the two elements; advance in the table FUS and in the table that contributed its element. When one of the two arrays A or B is exhausted, simply copy the remaining elements of the other array into the FUS array.


Difficulty level
Video recording
This exercise is mostly suitable for students
#include<stdio.h>
#include<conio.h>
#define SIZE 50
void main()
{
	int A[SIZE], B[SIZE], FUS[2*SIZE];
	int N, M; // dimensions for A and B
	int i, j, k;

	// Reading size and A values
	do {
		printf("Enter the dimension of A: ");
		scanf("%d", &N);
	} while (N <= 0 || N > SIZE);

	for (i = 0; i < N; i++)
	{
		printf("Enter A[%d]: ", i);
		scanf("%d", &A[i]);
	}


	// Reading size and B values
	do {
		printf("Enter the dimension of B: ");
		scanf("%d", &M);
	} while (M <= 0 || M > SIZE);

	for (i = 0; i < M; i++)
	{
		printf("Enter B[%d]: ", i);
		scanf("%d", &B[i]);
	}

	 

 	i=j=k=0;
 	while (i<N  && j<M)
        	if(A[i]<B[j])
			FUS[k++]=A[i++];
        	else
			FUS[k++]=B[j++];


	
 	while (i<N)
        	FUS[k++]=A[i++];
 	while (j<M)
       		FUS[k++]=B[j++];


	printf("\n\n** Array A ** \n");
	for (i = 0; i < N; i++)
	{
		printf("%4d", A[i]);
	}
	printf("\n\n** Array B ** \n");
	for (i = 0; i < M; i++)
	{
		printf("%4d", B[i]);
	}


	printf("\n\n** After merging ** \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 !!
Alexandrine multiplication