-
Notifications
You must be signed in to change notification settings - Fork 16
/
MergeSortedArray.java
33 lines (30 loc) · 949 Bytes
/
MergeSortedArray.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
public class MergeSortedArray {
public void merge(int[] array1, int n, int[] array2, int m) {
int[] result = new int[m + n];
for (int i = 0, j = 0, index = 0 ; i <= n && j <= m ; ) {
if (i == n) {
while (j < m) {
result[index++] = array2[j++];
}
break;
}
if (j == m) {
while (i < n) {
result[index++] = array1[i++];
}
break;
}
if (array1[i] < array2[j]) {
result[index++] = array1[i++];
} else {
result[index++] = array2[j++];
}
}
copyContentInto(array1, result);
}
private static void copyContentInto(int[] array, int[] from) {
for (int index = 0 ; index < array.length ; index++) {
array[index] = from[index];
}
}
}