Question #263879

Write a function by using priority queue to merge two sorted arrays. The function will accept two integer


arrays and their sizes as arguments and then will merge them in ascending order and display the three


arrays.

Expert's answer

int* merge(int* A, int n1, int* B, int n2) {
  int *merged = malloc(sizeof(int) * (n1 + n2));
  int i=0, j=0, k=0;
  while (i<n1 && j<n2)
    if (A[i] < B[j])
      merged[k++] = A[i++]; 
    else
      merged[k++] = B[j++];
  while (i<n1)
    merged[k++] = A[i++]; 
  while (j<n2)
    merged[k++] = B[j++];
  return merged;
}
LATEST TUTORIALS
APPROVED BY CLIENTS