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
Please find the solution for this problem:
#include <stdio.h>
#include <stdlib.h>
int main() {
int intA[ 18 ]={};
int intB[5]={};
int i,j,k,l;
int randomNumberForA=rand()%50;
int randomNumberForB=rand()%50;
for ( i = 0; i < 13; i++ ) {
intA[ i ] = randomNumberForA;
randomNumberForA=randomNumberForA+1;
}
for ( i = 0; i < 5; i++ ) {
intB[ i ] = randomNumberForB;
randomNumberForB=randomNumberForB+1;
}
for (j = 0; j < 18; j++ ) {
printf("Array A[%d] = %d\n", j, intA[j] );
}
printf("\n################\n");
for (j = 0; j < 5; j++ ) {
printf("Array B[%d] = %d\n", j, intB[j] );
}
printf("\n################\n");
int m=13;// Array A's filled integers count
for(l=0;l<5;l++){
for (j = 0; j < 18; j++ ) {
if(m>j){
if(intA[j] >=intB[l]){
//shift one place forward
for(k=m-1;k>=j;k--){
intA[k+1]=intA[k];
}
//assign b's index value in A's index
intA[j]=intB[l];
//counter for filled places in array A
m=m+1;
break;
}
}else{
intA[j]=intB[l];
m=m+1;
break;
}
}
}
printf("\n################\n");
for (j = 0; j < 18; j++ ) {
printf("Array A[%d] = %d\n", j, intA[j] );
}
return 0;
}