Learn Array manipulation and the basics of DSA. Merging arrays form the base for DSA along with LinkedList. This post covers the algorithm and the code for merging two arrays.
Algorithm
STEP 1: START
STEP 2:I=L1 ,J=L2 , K=L
STEP 3: WHILE(I<=U1&&J<=U2)DO
STEP 4: IF(A[I]<B[J])THEN
STEP 5: C[K]=A[I]
STEP 6: K=K+1
STEP 7: I=I+1
STEP 8: ELSE
STEP 9: C[K]=B[J]
STEP 10: J=J+1
STEP 11: K=K+1
STEP 12: ENDIF
STEP 13: ENDWHILE
STEP 14: WHILLE(I<=U1)DO
STEP 15: C[K]=A[I]
STEP 16: K=K+1
STEP 17: I=I+1
STEP 18: ENDWHILE
STEP 19: WHILE(J<=U2)DO
STEP 20: C[K]=B[J]
STEP 21: K=K+1
STEP 22: J=J+1
STEP 23: ENDWHILE
STEP 24: STOP
Code
#include <stdio.h>
void input();
void merge();
void printing();
int a[5];
int b[5];
int c[10];
int main(){
input();
merge();
printing();
return 0;
}
void merge(){
int i=0,j=0,k=0;
while(i<5 && j<5){
if(a[i]<b[j])
{
c[k]=a[i];
k++;
i++;
}
else
{
c[k]=b[j];
k++;
j++;
}
}
while(i<5){
c[k]=a[i];
k++;
i++;
}
while(j<5)
{
c[k]=b[j];
k++;
j++;
}
}
void printing(){
for(int i=0;i<10;i++)
{
printf(" %d ",c[i],",");
}
}
void input(){
for(int i=0;i<5;i++)
{ printf("a[%d]",i);
scanf("%d",&a[i]);
printf("b[%d]",i);
scanf("%d",&b[i]);
}
}
Output
user@computer$ : a[0]1
b[0]2
a[1]3
b[1]4
a[2]5
b[2]6
a[3]7s
b[3]8
a[4]9
b[4]10
1 2 3 4 5 6 7 8 9 10
Click here to get the algorithm and the code for reversing an array.
Click here to get the algorithm and the code for Merging two linked lists.