-
Notifications
You must be signed in to change notification settings - Fork 656
/
Copy pathMergeTwoSortedArraysJava
51 lines (48 loc) · 1.47 KB
/
MergeTwoSortedArraysJava
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
// Function to find next gap.
private static int nextGap(int gap)
{
if (gap <= 1)
return 0;
return (gap / 2) + (gap % 2);
}
private static void merge(int[] arr1,
int[] arr2, int n,
int m)
{
int i, j, gap = n + m;
for (gap = nextGap(gap); gap > 0;
gap = nextGap(gap))
{
// comparing elements in the first
// array.
for (i = 0; i + gap < n; i++)
if (arr1[i] > arr1[i + gap])
{
int temp = arr1[i];
arr1[i] = arr1[i + gap];
arr1[i + gap] = temp;
}
// comparing elements in both arrays.
for (j = gap > n ? gap - n : 0;
i < n && j < m;
i++, j++)
if (arr1[i] > arr2[j])
{
int temp = arr1[i];
arr1[i] = arr2[j];
arr2[j] = temp;
}
if (j < m)
{
// comparing elements in the
// second array.
for (j = 0; j + gap < m; j++)
if (arr2[j] > arr2[j + gap])
{
int temp = arr2[j];
arr2[j] = arr2[j + gap];
arr2[j + gap] = temp;
}
}
}
}