Merge While Sorting

# Merge While Sorting

### Write a program to create two arrays of size m and n, merge them into a third array while sorting them. You are not allowed to sort the array after merging.

import java.io.*; public class MergeInSortedOrder { public static void main(String ar[])throws Exception { BufferedReader ob=new BufferedReader( new InputStreamReader(System.in)); int i,j,k,m,y,n,t; System.out.println("Enter the Length of 1st array"); m=Integer.parseInt(ob.readLine()); int a[]=new int[m]; System.out.println("Enter "+m+" elements"); for(i=0;i< m;i++) a[i]=Integer.parseInt(ob.readLine()); //sorting the array in ascending order for(i=0;i< m;i++) { for(j=i+1;j< m;j++) { if(a[i]>a[j]) { t=a[i]; a[i]=a[j]; a[j]=t; } } } System.out.println("Enter the Length of 2nd array"); n=Integer.parseInt(ob.readLine()); int b[]=new int[n]; System.out.println("Enter "+n+" elements"); for(i=0;i< n;i++) b[i]=Integer.parseInt(ob.readLine()); //sorting the array in ascending order for(i=0;i< n;i++) { for(j=i+1;j< n;j++) { if(b[i]>b[j]) { t=b[i]; b[i]=b[j]; b[j]=t; } } } int c[]=new int[m+n]; i=j=k=0; //merging the two arrays in ascending order while(true) { if(a[i]< b[j]) { c[k++]=a[i]; i++; if(i==m) break; } else { c[k++]=b[j]; j++; if(j==n) break; } } if(i< m) { for(y=i;y< m;y++) c[k++]=a[y]; } if(j< n) { for(y=j;y< n;y++) c[k++]=b[y]; } System.out.println("The new array is"); for(i=0;i< m+n;i++) System.out.print(c[i]+" "); } }