-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeArrays.java
More file actions
44 lines (38 loc) · 1.19 KB
/
MergeArrays.java
File metadata and controls
44 lines (38 loc) · 1.19 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
import java.util.*;
public class MergeArrays {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter length of array 1");
int n1 = sc.nextInt();
int[] a = new int[n1];
System.out.println("Enter elements of array 1");
for (int i = 0; i < n1; i++) {
a[i] = sc.nextInt();
}
System.out.println("Enter length of array 2");
int n2 = sc.nextInt();
int[] b = new int[n2];
System.out.println("Enter elements of array 2");
for (int i = 0; i < n2; i++) {
b[i] = sc.nextInt();
}
int i = 0, j = 0, k = 0;
int[] result = new int[n1 + n2];
while (i < n1 && j < n2) {
if (a[i] < b[j]) {
result[k] = a[i];
i++;
k++;
} else
result[k++] = b[j++];
}
// remaining elements
while (i < n1)
result[k++] = a[i++];
while (j < n2)
result[k++] = b[j++];
for (int ele : result) {
System.out.print(ele + " ");
}
}
}