Use of second while loop in merge function

while(i<=mid)
{
temp[k++]=a[i++];
}
while(j<=e)
{
temp[k++]=a[j++];
}
for(i=s;i<=e;i++)
{
a[i]=temp[i];
}
I can’t understand tat why have written this part when already the sorted elements were inserted in the previous while part

@gkritika898 The first while loop while(i<=mid) is for the remaining elements in the first half.
The second while loop while(j<=e) is for the remaining elements in the second part.
Consider 2 sorted arrays:
[ 3,5,7,9] and [1,2,4]
On performing merge sort:
after inserting 1,2,3,4 in the temp array the pointer j which was for iterating 2nd sorted array reaches to the end
and pointer i which was for iterating 1st sorted array is at 1st position( at element 5). So for pushing the remaining elements in the temp array, these while loop are used.

Hope you understand :slightly_smiling_face:

Thank you so much, now I understood where I was getting wrong.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.