In: Computer Science
Write a C program.
Problem 1: You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order without using any other array space. Implementation instruction:
(1) Define one array of size 18 for A and the other array of size 5 for B.
(2) Initialize A by inputting 13 integers in the ascending order, and Initialize B by inputting 5 integers in the ascending order. (Note: don’t hard code the integers of the arrays.)
(3) Merge B with A in a way all values are sorted.
(4) Print out the updated array A, after merging with B. For example: If your input for A is 1, 3, 11, 15, 20, 25, 34, 54, 56, 59, 66, 69, 71 and your input for B is 2, 4, 5, 22, 40 Finally, after merging A and B, A becomes 1, 2, 3, 4, 5, 11, 15, 20, 22, 25, 34, 40, 54, 56, 59, 66, 69, 71
The answer to this question is as follows:
The code is as follows:
#include<stdio.h>
void mergeArrays(int A[], int B[], int size_1,
int size_2, int C[])
{
int i = 0, j = 0, k = 0;
while (i<size_1 && j <size_2)
{
//check if the first array element
is greate than the
//second array element if condition
is true then
//increment the result array and A
array index otherwise
//increment the B array index
if (A[i] < B[j])
C[k++] =
A[i++];
else
C[k++] =
B[j++];
}
//To store the elements that are left in A
array
while (i < size_1)
C[k++] = A[i++];
// To store the elements that are left in B
array
while (j < size_2)
C[k++] = B[j++];
}
// Driver code
int main()
{
int A[18],B[5],size_A,size_B;
printf("Enter the size of the Array A:");
scanf("%d",&size_A);
printf("Enter the elements into array A:");
for(int i=0;i<size_A;i++)
{
scanf("%d",&A[i]);
}
printf("Enter the size of the Array B:");
scanf("%d",&size_B);
printf("Enter the elements into array B:");
for(int i=0;i<size_B;i++)
{
scanf("%d",&B[i]);
}
int result[size_A+size_B];
mergeArrays(A, B, size_A, size_B, result);
//cout << "Array after merging"
<<endl;
for (int i=0; i < size_A+size_B; i++)
printf("%d ",result[i]);
return 0;
}
The input and output are provided in the screenshot below: