Merge two sorted arrays

QUESTION

Given two sorted arrays, the task is to merge them in a sorted manner.

“TESTCASE_1”: “5 4\n1 2 4 9 15\n2 3 7 8\n###—###SEPERATOR—###—\n1 2 2 3 4 7 8 9 15”, “TESTCASE_2”: “5 6\n1 2 4 9 15\n2 3 7 8 18 20\n###—###SEPERATOR—###—\n1 2 2 3 4 7 8 9 15 18 20”, “TESTCASE_3”: “4 2\n-8 4 6 10\n-9 -7\n###—###SEPERATOR—###—\n-9 -8 -7 4 6 10”, “TESTCASE_4”: “2 0\n1 2\n###—###SEPERATOR—###—\n1 2”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

// Java program to merge two sorted arrays
import java.util.*;
import java.lang.*;
import java.io.*;
 
class TestClass
{
    // Merge arr1[0..n1-1] and arr2[0..n2-1] 
    // into arr3[0..n1+n2-1]
    public static void mergeArrays(int[] arr1, int[] arr2, int n1,
                                int n2, int[] arr3)
    {
        int i = 0, j = 0, k = 0;
     
        // Traverse both array
        while (i<n1 && j <n2)
        {
            // Check if current element of first
            // array is smaller than current element
            // of second array. If yes, store first
            // array element and increment first array
            // index. Otherwise do same with second array
            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) 
    {
      Scanner sc=new Scanner(System.in);
      int n1=sc.nextInt();
      int n2=sc.nextInt();
      int arr1[]=new int[n1];
      int arr2[]=new int[n2];
      for(int i=0;i<n1;i++)
        arr1[i]=sc.nextInt();
      for(int i=0;i<n2;i++)
        arr2[i]=sc.nextInt();
     
        
     
        int[] arr3 = new int[n1+n2];
         
        mergeArrays(arr1, arr2, n1, n2, arr3);
     
       
        for (int i=0; i < n1+n2; i++)
            System.out.print(arr3[i] + " ");
    }
}
 
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.