Merge Two Arrays
========================================================================
#include <stdio.h>
#include<conio.h>
#include<iostream>
using namespace std;
void merge(int [], int, int [], int, int []);
main()
{
int a[100], b[100], m, n, c, sorted[200];
cout<<"Input number of elements in first array\n";
cin>>m;
cout<<"Enter Integers";
for (c = 0; c < m; c++) {
cin>>a[c];
}
cin>>n;
cout<<"enter integer"<<n;
for (c = 0; c < n; c++) {
cin>>b[c];
}
merge(a, m, b, n, sorted);
cout<<"sorted array";
for (c = 0; c < m + n; c++)
{
cout<<sorted[c];
}
}
void merge(int a[], int m, int b[], int n, int sorted[])
{
int i, j, k;
j = k = 0;
for (i = 0; i < m + n;) {
if (j < m && k < n) {
if (a[j] < b[k]) {
sorted[i] = a[j];
j++;
}
else {
sorted[i] = b[k];
k++;
}
i++;
}
else if (j == m) {
for (; i < m + n;) {
sorted[i] = b[k];
k++;
i++;
}
}
else {
for (; i < m + n;) {
sorted[i] = a[j];
j++;
i++;
}
}
}
}
========================================================================
- Blogger Comment
- Facebook Comment
Subscribe to:
Post Comments
(
Atom
)
0 comments:
Post a Comment