-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay4.java
More file actions
55 lines (43 loc) · 1.49 KB
/
Copy pathDay4.java
File metadata and controls
55 lines (43 loc) · 1.49 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
48
49
50
51
52
53
54
55
import java.util.Arrays;
public class MergeTwoSortedArrays {
private static int nextGap(int gap) {
if (gap <= 1) return 0;
return (gap / 2) + (gap % 2);
}
public static void merge(int[] arr1, int[] arr2, int m, int n) {
int gap = m + n;
for (gap = nextGap(gap); gap > 0; gap = nextGap(gap)) {
int i, j;
for (i = 0; i + gap < m; i++) {
if (arr1[i] > arr1[i + gap]) {
int temp = arr1[i];
arr1[i] = arr1[i + gap];
arr1[i + gap] = temp;
}
}
for (j = gap > m ? gap - m : 0; i < m && j < n; i++, j++) {
if (arr1[i] > arr2[j]) {
int temp = arr1[i];
arr1[i] = arr2[j];
arr2[j] = temp;
}
}
if (j < n) {
for (j = 0; j + gap < n; j++) {
if (arr2[j] > arr2[j + gap]) {
int temp = arr2[j];
arr2[j] = arr2[j + gap];
arr2[j + gap] = temp;
}
}
}
}
}
public static void main(String[] args) {
int[] arr1 = {1, 3, 5, 7};
int[] arr2 = {2, 4, 6, 8};
merge(arr1, arr2, arr1.length, arr2.length);
System.out.println("arr1 = " + Arrays.toString(arr1));
System.out.println("arr2 = " + Arrays.toString(arr2));
}
}