Merging of Two Arrays in C
C Program for Merge Sort.Learn to merge two sorted arrays into a single array so that the resulting merged array is also in sorted form.
Array1 = 1 , 3 , 5 Array2 = 2 , 4 , 7 , 9 CombinedArray = 1 , 3 , 5 , 2 , 4 , 7 , 9
Let’s assume there are two arrays, p and q, of a certain length. The length of the two arrays can differ.The merged array that will be created from the sorted elements of the preceding two arrays will be called array r.
-
The element at
p[i]
is compared with the element atq[j]
. Ifp[i]
is less thanq[j]
, thenp[i]
is assigned to arrayr
.Same forq[j]
is with np[i]
, thenq[j]
is assigned to arrayr
. -
If
p[i]
is equal toq[j]
, then both the elements are assigned to array r.p[i]
is added tor[k]
.The values of thei
andk
indices are incremented.q[j]
is also added tor[k]
, and the indices of theq
andr
arrays are incremented.
#include <stdio.h> #define max 100 void main() { int p[max], q[max], r[max]; int m, n; int i, j, k; printf("Enter length of first array:"); scanf("%d", &m); printf("Enter %d elements of the first array in sorted order \n", m); for (i = 0; i < m; i++) scanf("%d", &p[i]); printf("\nEnter length of second array:"); scanf("%d", &n); printf("Enter %d elements of the second array in sorted order\n", n); for (i = 0; i < n; i++) scanf("%d", &q[i]); i = j = k = 0; while ((i < m) && (j < n)) { if (p[i] < q[j]) { r[k] = p[i]; i++; k++; } else { if (q[j] < p[i]) { r[k] = q[j]; k++; j++; } else { r[k] = p[i]; k++; i++; r[k] = q[j]; k++; j++; } } } while (i < m) { r[k] = p[i]; k++; i++; } while (j < n) { r[k] = q[j]; k++; j++; } printf("\nThe combined sorted array is:\n"); for (i = 0; i < k; i++) printf("%d\n", r[i]); }
Enter length of first array:3 Enter 3 elements of the first array in sorted order 1 2 4 Enter length of second array:4 Enter 4 elements of the second array in sorted order 5 6 7 8 The combined sorted array is: 1 2 4 5 6 7 8