Reputation: 21
Here is the main portion of my code where "while" loop:
while(ind1<n1.length && ind2<n2.length)
{
if(ncm!=null)
{
if(n1[ind1]<ncm)
{
s1=s1+n1[ind1];
ind1++;
}
else if(n2[ind2]<ncm)
{
s2=s2+n2[ind2];
ind2++;
}
else if(n2[ind2]==ncm && n1[ind1]==ncm)
{
s2=s2+n2[ind2];
s1=s1+n1[ind1];
if(s1>s2)
s2=s1;
else if(s2>s1)
s1=s2;
ind1++;
ind2++;
ncm=q.poll();
}
}
else
{
s1=s1+n1[ind1];
ind1++;
s2=s2+n2[ind2];
ind2++;
}
System.out.println("ind1 "+ind1+" ind2 "+ind2);
System.out.println("s1 "+s1+" s2 "+s2);
}
I am passing these two arrays: int n1[]= {1,2,3,4}; int n2[]= {10,11};
I have observed which array has minimum elements the loop is getting terminated upto that last index of the minimum array while I want it may continue till it reaches both the array's last element. Isn't this condition suffice ? " while(ind1<n1.length && ind2<n2.length) "
Upvotes: 0
Views: 58
Reputation: 1604
If you want to reach the end of both arrays, you should add conditional OR instead of AND:
while(ind1<n1.length || ind2<n2.length)
Upvotes: 0
Reputation: 263
No, this condition
while(ind1<n1.length && ind2<n2.length)
Will mean that if one of the comparisons ends up false, the while loop will end. That will happen when it reaches the shortest array's last element. Instead, if you want to continue until it reaches the longest array' last element, it should be:
while(ind1<n1.length || ind2<n2.length)
Upvotes: 2