Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 38: Write a Java program to perform merge two arrays.

Merge.java

import java.util.Scanner;

//Class SelectionSort contains the method to perform InsertionSort.
class MergeArrays
{
	public static int[] merge(int arr1[], int arr2[])
	{
		int total[]= new int[arr1.length+arr2.length];
		int i=0,j=0,k=0;

		while(i < arr1.length && j < arr2.length)
		{
			if(arr1[i]<=arr2[j])
			{
				total[k]=arr1[i];
				i++;
				k++;
			}
			else
			{
				total[k]=arr2[j];
				j++;
				k++;
			}
		}

		while(i < arr1.length)
		{
			total[k]=arr1[i];
			k++;
			i++;
		}

		while(j < arr2.length)
		{
			total[k]=arr2[j];
			k++;
			j++;
		}
		return total;
    }
}

public class Merge
{
	//Method to take input.
	public static int[] takeInput()
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the number of elements to be included in the array.");
		int size = s.nextInt();
		int arr[] = new int[size];
		
		System.out.println("Enter the element in the array");
		for (int i = 0; i < size; i++)
		{
			arr[i] = s.nextInt();
		}
		return arr;
	}
	
	//Method to print sorted array.
	public static void print(int[] arr)
	{
		for (int i = 0; i < arr.length; i++)
		{
			System.out.print(arr[i]+" ");
		}
	}
	
	//Main method.
	public static void main(String[] args)
	{
		int[] arr1 = takeInput();
		int[] arr2 = takeInput();
		int ans[] = MergeArrays.merge(arr1, arr2);
		System.out.println("Array after merging");
		print(ans);
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.