Java Program to merge two sorted array

To merge two sorted array we use the idea of Merge sort.In this approach, we create a array of length which is sum of length of first array and length of second array.

Then simultaneously traverse both array and pick the smallest element by comparing first array and second array and copy that element in third array.After that if there are remaining elements in first or second array,copy them also in third array.


Input:

arr1- 1,4,6,10

arr2- 2,5,8,9


Output:

1,2,4,5,6,8,9,10


Implementation Using Java:

public class MergeArray {
	
	public static int[] merge(int[] arr1,int[] arr2)
	{
		int m= arr1.length;
		int n= arr2.length;
		
		int[] arr3= new int[m+n];
		int i=0;
		int j=0;
		int k=0;
		
		while(i<m && j<n)
		{
			if(arr1[i]<=arr2[j])
			{
				arr3[k]=arr1[i];
				i++;
				k++;
			}
			else
			{
				arr3[k]=arr2[j];
				j++;
				k++;
			}
		}
		while(i<m)
		{
			arr3[k]=arr1[i];
			i++;
			k++;
			
		}
		while(j<n)
		{
			arr3[k]=arr2[j];
			j++;
			k++;
		}
		return arr3;
	}

	public static void main(String[] args) {
		
		int arr1[]= {1,4,6,10};
		int arr2[]= {2,5,8,9};
		
		int arr3[]= merge(arr1,arr2);
		
		System.out.print("Array after merging: "+"  ");


		for(int i=0;i<arr3.length;i++)
		{
		System.out.print(arr3[i]+" ");
		}
	}

}

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find anything incorrect, or you want to share more information about the topic discussed.


Follow Programmers Door for more.

#blog #interview #placement #learn #computer #science


        Contact Us

programmersdoor@gmail.com

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door