forked from mayankchaudhary26/HacktoberFest-Practice-2021
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_Two_Sorted_Array.java
More file actions
47 lines (42 loc) Β· 1.01 KB
/
Merge_Two_Sorted_Array.java
File metadata and controls
47 lines (42 loc) Β· 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import java.util.*;
public class Merge_Two_Sorted_Array {
public static int[] mergeTwoSortedArrays(int[] a, int[] b){
int i=0,j=0,k=0;
int [] ans = new int[a.length + b.length];
while(i < a.length && j < b.length){
if(a[i] < b[j]){
ans[k++] = a[i++];
}
else {
ans[k++] = b[j++];
}
}
while(i < a.length){
ans[k++] = a[i++];
}
while(j < b.length){
ans[k++] = b[j++];
}
return ans;
}
public static void print(int[] arr){
for(int i = 0 ; i < arr.length; i++){
System.out.println(arr[i]);
}
}
public static void main(String[] args){
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] a = new int[n];
for(int i = 0 ; i < n; i++){
a[i] = scn.nextInt();
}
int m = scn.nextInt();
int[] b = new int[m];
for(int i = 0 ; i < m; i++){
b[i] = scn.nextInt();
}
int[] mergedArray = mergeTwoSortedArrays(a,b);
print(mergedArray);
}
}