101k views
4 votes
Write a function merge that merges two lists into one, alternating elements from each list until the end of one of the lists has been reached, then appending the remaining elements of the other list.

1 Answer

2 votes

Step-by-step explanation:

The program that merges two lists or two arrays is written below;

Code :

void main void

{

char [] arr1= {'1','2','3'};

char [] arr2= {'a','b','c','d','e'};

int l1= arr1.length;

int l2=arr2.length;

int l3=l1+l2;

char [] arr3=new char[l1+l2];

int i=0;

int j=0;

int k=0;

int m=0;

int r=0;

if(l1<l2)

r=l1;

else

r=l2;

while(m<r)

{

arr3[k++]=arr1[i++];

arr3[k++]=arr2[j++];

m++;

}

while(k<l3)

{

if(l1<l2)

arr3[k++]=arr2[j++];

else

arr3[k++]=arr1[i++];

}

for(int n=0;n<l3;n++)

{

System.out.print(arr3[n]+" ");

}

}

User Nicola
by
4.8k points