Answer to Question #309541 in Java | JSP | JSF for Kyle

Question #309541

Given two sorted arrays A and B of size p and q, write a Java program to merge elements of A with B by maintaining the sorted order i.e. fill A with first p smallest elements and fill B with remaining elements.


1
Expert's answer
2022-03-14T02:37:32-0400
public static void mergeArrays(int[] arr1, int[] arr2, int n1, int n2, int[] arr3)
{
    int i = 0, j = 0, k = 0;
    while (i<n1 && j <n2) {
        if (arr1[i] < arr2[j])
            arr3[k++] = arr1[i++];
        else
            arr3[k++] = arr2[j++];
    }

    // Store remaining elements of first array
    while (i < n1)
        arr3[k++] = arr1[i++];

    // Store remaining elements of second array
    while (j < n2)
        arr3[k++] = arr2[j++];
}

public static void main (String[] args) {
    int[] arr1 = {1, 3, 5, 7};
    int n1 = arr1.length;

    int[] arr2 = {2, 4, 6, 8};
    int n2 = arr2.length;

    int[] arr3 = new int[n1+n2];

    mergeArrays(arr1, arr2, n1, n2, arr3);

    System.out.println("Array after merging");
    for (int i=0; i < n1+n2; i++)
        System.out.print(arr3[i] + " ");
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS