-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeArrays.java
82 lines (68 loc) · 2.02 KB
/
MergeArrays.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class MergeArrays
{
/* Function to move m elements at the end of array mPlusN[] */
void moveToEnd(int mPlusN[], int size)
{
int i, j = size - 1;
for (i = size - 1; i >= 0; i--)
{
if (mPlusN[i] != -1)
{
mPlusN[j] = mPlusN[i];
j--;
}
}
}
// Merges array N[] of size n into array mPlusN[] of size m+n
void merge(int mPlusN[], int N[], int m, int n)
{
int i = n;
// Current index of i/p part of mPlusN[]
int j = 0;
// Current index of N[]
int k = 0;
// Current index of of output mPlusN[]
while (k < (m + n))
{
/* Take an element from mPlusN[] if
a) value of the picked element is smaller and we have
not reached end of it
b) We have reached end of N[] */
if ((i < (m + n) && mPlusN[i] <= N[j]) || (j == n))
{
mPlusN[k] = mPlusN[i];
k++;
i++;
}
else // Otherwise take element from N[]
{
mPlusN[k] = N[j];
k++;
j++;
}
}
}
/* Utility that prints out an array on a line */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
public static void main(String[] args)
{
MergeArrays ma = new MergeArrays();
/* Initialize arrays */
int mPlusN[] = {2, 8, -1, -1, -1, 13, -1, 15, 20};
int N[] = {5, 7, 9, 25};
int n = N.length;
int m = mPlusN.length - n;
/*Move the m elements at the end of mPlusN*/
ma.moveToEnd(mPlusN, m + n);
/*Merge N[] into mPlusN[] */
ma.merge(mPlusN, N, m, n);
/* Print the resultant mPlusN */
ma.printArray(mPlusN, m + n);
}
}