Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Created June 1, 2017 10:07
Show Gist options
  • Save rupalbarman/fb52bd2859a325531617c53c7e81c4c2 to your computer and use it in GitHub Desktop.
Save rupalbarman/fb52bd2859a325531617c53c7e81c4c2 to your computer and use it in GitHub Desktop.
Merge two arrays (sorted) with no repetitions of values
#include <iostream>
using namespace std;
void merge_em_all(int *a, int *b, int *c, int x, int y, int z) {
int i=0, j=0, k= 0;
for(i=0, j=0; i<x && j<y; ) {
if(a[i]< b[j]){
c[k++]= a[i];
a[i]=-1;
i++;
} else if(a[i]> b[j]) {
c[k++]= b[j];
b[j]=-1;
j++;
} else {
c[k++]= a[i];
a[i]=-1;
b[j]=-1;
j++;
i++;
}
}
int xx=0;
while (xx< x){
if(a[xx]!=-1)
c[k++]= a[xx];
xx++;
}
xx=0;
while (xx< y){
if(b[xx]!=-1)
c[k++]= b[xx];
xx++;
}
}
int main() {
int a[]= {2,4,5,6,7,9,13};
int b[]= {2,3,4,7,8,10,12};
int n1= sizeof(a)/sizeof(int);
int n2= sizeof(b)/sizeof(int);
int n3= n1+n2;
int c[n3];
merge_em_all(a,b,c,n1,n2,n3);
for(int i=0; c[i]!='\0'; i++){ // \0 is null for all arrays
cout<<c[i]<<" ";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment