Program to merge two sorted arrays.
#include <stdio.h>
void merge(int [], int, int [], int, int []);
int main() {
int a[100], b[100], m, n, c, sorted[200];
printf("Input number of elements in first array:");
scanf("%d", &m);
printf("Input %d integers(sorted)\n", m);
for (c = 0; c < m; c++) {
scanf("%d", &a[c]);
}
printf("Input number of elements in second array\n");
scanf("%d", &n);
printf("Input %d integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d", &b[c]);
}
merge(a, m, b, n, sorted);
printf("Merged Sorted array:\n");
for (c = 0; c < m + n; c++) {
printf("%d\t", sorted[c]);
}
return 0;
}
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++;
}
}
}
}
Output:
Input number of elements in first array:3
Input 3 integers(sorted)
12 45 78
Input number of elements in second array
5
Input 5 integers
11 23 35 56 91
Merged Sorted array:
11 12 23 35 45 56 78 91
Tuesday, February 10, 2015
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment