Merge Two Sorted Arrays
You have been given two sorted arrays/lists(ARR1 and ARR2) of size N and M respectively, merge them into a third array/list such that the third array is also sorted.
Sample Input 1 :
Sample Output 1 :
3
1 3 6
4
2 7 8 9
Merged Array ->
1 2 3 6 7 8 9
import java.util.Scanner; public class MergeSortedArray { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n=s.nextInt(); int a[]=new int[n]; for(int i=0;i<n;i++) { a[i]=s.nextInt(); } int m=s.nextInt(); int b[]=new int[m]; for(int i=0;i<m;i++) { b[i]=s.nextInt(); } int c[]=merge(a, b); print(c); } public static void print(int a[]) { System.out.println("Merged Array -> "); for(int i=0;i<a.length;i++) { System.out.print(a[i]+" "); } } public static int[] merge(int arr1[], int arr2[]) { int l1=arr1.length; int l2=arr2.length; int l=l1+l2; int arr3[]=new int[l]; int k=0; int i=0; int j=0; while(i<l1 && j<l2) { if(arr1[i]<=arr2[j]) { arr3[k]=arr1[i]; k++; i++; } else { arr3[k]=arr2[j]; k++; j++; } } while(i<l1) { arr3[k]=arr1[i]; i++; k++; } while(j<l2) { arr3[k]=arr2[j]; j++; k++; } return arr3; } }
Comments
Post a Comment