





Please login
Prime

Prepinsta Prime
Video courses for company/skill based Preparation
(Check all courses)
Get Prime Video
Prime

Prepinsta Prime
Purchase mock tests for company/skill building
(Check all mocks)
Get Prime mock
Merging two sorted arrays

Merging two sorted arrays In Java.
Problem Statement :
Given two sorted arrays, the task is to merge them in a sorted manner.
Example :
Input:
arr1[ ] = { 5, 8, 9}
arr2[] = {4, 7, 8}
Output:
arr3[] = {4, 5, 7, 8, 8, 9}
Algorithm:
- Create an array arr3[] of size n1 + n2.
- Copy all n1 elements of arr1[] to arr3[]
- Traverse arr2[] and one by one insert elements of arr3[] to arr1[]. This step takes O(n1 * n2) time.
Java code :
// Java program to merge two sorted arrays
import java.util.*;
import java.lang.*;
import java.io.*;
class prepinsta
{
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)
{
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 = { 5, 8, 9};
int n1 = arr1.length;
int[] arr2 = {4, 7, 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] + ” “);
}
}
Output:
Array after merging 1 2 3 4 5 6 7 8
Login/Signup to comment