-
Notifications
You must be signed in to change notification settings - Fork 1
/
MergeTwoSortedArrays.java
67 lines (50 loc) · 1.19 KB
/
MergeTwoSortedArrays.java
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.io.*;
import java.util.*;
public class Main {
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];
i++;
k++;
}else{
ans[k] = b[j];
j++;
k++;
}
}
while(i < a.length){
ans[k] = a[i];
k++;
i++;
}
while(j < b.length){
ans[k] = b[j];
k++;
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);
}
}