Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java Program to Merge Two Arrays

Problem Statement : To Merge two arrays in ascending order.

Algorithm

1) Start.
2) Initialize the arrays A[ ], B[ ] and C[ ].
3) Read the limit of the first array A[ ].
4) Read the elements of the array A[ ].
5) Read the limit of the second array B[ ].
6) Read the elements of the array B[ ].
7) Repeat step 8 for i=0 to m
8) Repeat step 9 for j=i+1 to n
9) If A[i] =0 and j>=0 else go to 21.
22) If A[i]B[j] then C[k] = B[j], j= j-1
27) Repeat step 22 if i>=0 else goto 23.
28) C[k]=A[i], k = k+1, i=i-1.
29) Repeat step 24 if j>=0 else goto 25.
30) C[k]=B[j], k = k+1, j=j-1.
31) Print the merged array C[ ] sorted in ascending order.
32) Stop.

Program
import java.io.*;

class Merge
{
	private int l1,l2,lr;
	private String s1[],s2[],so[];
	DataInputStream in = new DataInputStream(System.in);
	public void GetData()
	{
		int i;
		try
		{
			System.out.println("\nEnter the number of string in array 1");
			l1=Integer.parseInt(in.readLine());
			s1=new String[l1];
			System.out.println("\nEnter " + l1 +" strings");
			for(i=0;i=0)
					{
						st=s[j];
						s[j]=s[j+1];
						s[j+1]=st;	
					}
				}
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
	
	public void Merge()
	{
		
		int i1,i2,i;
		Sort(s1,l1);
		Sort(s2,l2);
		lr=l1+l2;
		i1=l1-1;
		i2=l2-1;
		so=new String[lr];
		System.out.println(lr);
		try
		{
			for(i=0;i=0))
				{
					so[i]=s1[i1];
					i1--;
				}
				else if(i2!=-1)
				{
					so[i]=s2[i2];
					i2--;
				}
				else
				{
					so[i]=s1[i1];
					i1--;
				}
			}
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
}

class MyMerge
{
	public static void main(String args[])
	{
		Merge m= new Merge();
		m.GetData();
		m.Merge();
		m.DisplayData();
	}
}
Output

Enter the number of string in array 1
3

Enter 3 strings
30
25
90

Enter the number of string in array 2
5

Enter 5 strings
95
31
30
55
63
8

First Array
————–
25
30
90

Second Array
————–
30
31
55
63
95

Merged Array
————–
95
90
63
55
31
30
30
25

Java Program to Merge Two Arrays is a post from ShoutToWorld - Let's Learn Let's Shout - Helping bloggers and developers.



This post first appeared on ShoutToWorld, please read the originial post: here

Share the post

Java Program to Merge Two Arrays

×

Subscribe to Shouttoworld

Get updates delivered right to your inbox!

Thank you for your subscription

×