WAP in C program to merge two sorted arrays

This is a C program that merge two arrays into third array,
Arrays are assumed to be sorted in ascending order.
User need to enter two short sorted arrays and the program displays the a large array merging both.

Copy the code below and compile it:

  
#include <stdio.h>
void func(int [], int, int [], int, int []);

int main() 
{
  int p[100], q[100], m, n, c, sorted[200];
  printf("Enter number of elements in 1st array\n");
  scanf("%d", &m);
  printf("Enter %d integers\n", m);
  for (c = 0; c < m; c++) {
  scanf("%d", &p[c]);
  }
  printf("Enter number of elements in second array\n");
  scanf("%d", &n);
  printf("Enter %d integers\n", n);
  for (c = 0; c < n; c++) {
  scanf("%d", &q[c]);
  }
  func(p, m, q, n, sorted);
  printf("After Sorting array:\n");
  for (c = 0; c < m + n; c++) {
  printf("%d\n", sorted[c]);
  }
  return 0;
}
 
void func(int p[], int m, int q[], int n, int sorted[]) {
int i, j, k;
j = k = 0;

for (i = 0; i < m + n;) {
if (j < m && k < n) {
if (p[j] < q[k]) {
sorted[i] = p[j];
j++;
}
else {
sorted[i] = q[k];
k++;
}
i++;
}
else if (j == m) {
for (; i < m + n;) {
sorted[i] = q[k];
k++;
i++;
}
}
else {
for (; i < m + n;) {
sorted[i] = p[j];
j++;
i++;
}
}
}
}

Post a Comment

0 Comments