Showing posts with label merge two sorted arrays. Show all posts
Showing posts with label merge two sorted arrays. Show all posts

C program to merge two sorted arrays. Array Union

//C/C++/C Plus Plus program to merge two sorted arrays
//C/C++/C Plus Plus program to find union of two sorted arrays
#include<iostream>
using namespace std;
#include<stdio.h>

int arrayIntersection(int arr1[],int arr2[],int n1,int n2);
int main()
{
cout<<"manin()\n";
int arr1[]={1,2,3,4,5};
int arr2[]={3,5,7,8,9};
int n1; n1=sizeof(arr1)/sizeof(arr1[0]);
int n2; n2=sizeof(arr2)/sizeof(arr2[0]);
arrayIntersection(arr1,arr2,n1,n2);
return 0;
}
int arrayIntersection(int arr1[],int arr2[],int n1,int n2)
{
int i=0,j=0;
while(i<n1 && j<n2)//while any of the array has elt
{
if(arr1[i]<arr2[j])
{
printf("%d",arr1[i]);
i++;
}
else if(arr2[j]<arr1[i])
{
printf("%d",arr2[j]);
j++;
}
else //arr[i]==arr[j]
{
printf("%d",arr2[j]);
i++;
j++;
}
}
while(i<n1)
printf("%d",arr1[i++]);
while(j<n2)
printf("%d",arr2[j++]);

cout<<endl;
}
//output
//12345789

How to merge two sorted arrays in C Language

/*Merging two sorted arrays:
input: two sorted arrays a and b and 1 output array c
1.compare a and b, if a[i]< c[k] put that in c[k] else put b[j]in c[k]
2.when any of array is empty put the remaining elements of other array's
elements in C as it is.*/
#include<stdio.h>
#include<stdlib.h>
void mergeSorted(int a[], int b[], int c[], int asize, int bsize, int
csize);

int main()
{
int i;
int a[]={5,10,15,20,25};
int b[]={2,4,6,8,10};
int c[10];
mergeSorted(a,b,c,5,5,10);
printf("Merged Array is:\n");
for(i=0;i<10;i++)
{
printf("%d ",c[i]);/* 2 4 5 6 8 10 10 15 20 25 */
}

printf("\n\n");
return 0;
}

void mergeSorted(int *a, int *b, int *c, int asize, int bsize, int csize)
{
printf("\nin mergeSorted:\n");
int ai=0,bi=0,ci=0,i;
//csize=asize+bsize;
/*compare a[ai]<b[bi] till any of the array ends.*/
while((ai<asize) && (bi<bsize))
{
if(a[ai]<=b[bi])
{
c[ci]=a[ai];
ci++;
ai++;
}
else
{
c[ci]=b[bi];
ci++;
bi++;
}
}
if(ai>=asize)
for(i=ci;i<csize;i++,bi++)
c[i]=b[bi];

else if(bi>=bsize)
for(i=ci;i<csize;i++,ai++)
c[i]=a[ai];


}