-1

I wrote this code.

#include<iostream>
using namespace std;
int main()
{int n1,n2;
cin>>n1>>n2;
int arr1[n1],arr2[n2];
for (int i=0;i<n1;i++)
cin>>arr1[i];
for (int j=0;j<n2;j++)
cin>>arr2[j];
int arr3[n1+n2],c1=0,c2=0,c3=0;
while (c1<n2 & c2<n2)
{if (arr1[c1]<=arr2[c2])
{arr3[c3]=arr1[c1];
c1++;
c3++;
}
else { arr3[c3]=arr2[c2];
c2++;
c3++;
}
while (c1<n1)
{arr3[c3]=arr1[c1];
c1++;
c3++;
}
while (c2<n2)
{arr3[c3]=arr2[c2];
c2++;
c3++;
}

}
for (int g=0;g<n1+n2;g++)
cout<<arr3[g];
return 0;
}

but it is not giving the required output. When I saw the same code in Java, it was given the same algorithm. What is problem with this code?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Fawkes4494d3
  • 111
  • 4
  • What *is* the output? And what output did you expect instead? – Hexaholic Dec 06 '15 at 10:57
  • oh i am very sorry, i wanted to get {1,2,3,4,5} on inputting {2,4,5} and {1,3} but i got {1,2,3,4} plus some garbage values and no 5. actually i got the typing error. i wrote (c1 – Fawkes4494d3 Dec 09 '15 at 15:51

1 Answers1

0

Merging two sorted vectors is relatively straight forward. Here is a psuedocode example that will take two vectors in ascending order and merge into another vector in ascending order.

Input: Sorted arrays A, B
Output: Merged array C

while((iterator on A is valid)&&(iterator on B is valid)):
    if (elem in A < elem in B):
        insert elem in A into C
        increment iterator on A
    else:
        insert elem in B into C
        increment iterator on B

while (iterator on A is valid):
    insert element in A into C
    increment iterator on A
while (iterator on B is valid):
    insert element in B into C
    increment iterator on B
return C

The first loop iterates over elements of A and B, copying the smallest element into C until at least ONE of them is exhausted. Once we know that we have processed all of the elements in at least one of the lists we just want to copy the remaining elements of the other list into C. That is what the bottom two loops do.

Edit:

After looking at your code a bit, some specific problems with your code could come from the first loop. You are using bitwise AND instead of the logical AND.

Also the declaration of arr3 is in error. C++ only allows array size initialization with compile-time constants. See This post for a more in depth description of that problem.

Community
  • 1
  • 1
Tanner
  • 88
  • 1
  • 6
  • i had a typing error.... i entered the (iterator on A condition) and the (iterator on B condition ) by mistake. actually it compiled so i could not understand. anyway i got it. thanks for the help and your time. – Fawkes4494d3 Dec 09 '15 at 15:53