-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeArrays.java
More file actions
33 lines (32 loc) · 960 Bytes
/
Copy pathMergeArrays.java
File metadata and controls
33 lines (32 loc) · 960 Bytes
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
package day29;
public class MergeArrays {
public static int[] merge(int[] arr1, int[] arr2) {
int n1 = arr1.length;
int n2 = arr2.length;
int[] mergedArray = new int[n1 + n2];
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
if (arr1[i] <= arr2[j]) {
mergedArray[k++] = arr1[i++];
} else {
mergedArray[k++] = arr2[j++];
}
}
while (i < n1) {
mergedArray[k++] = arr1[i++];
}
while (j < n2) {
mergedArray[k++] = arr2[j++];
}
return mergedArray;
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8};
int[] result = merge(arr1, arr2);
System.out.println("Merged array: ");
for (int i : result) {
System.out.print(i + " ");
}
}
}