forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMergeArrayOfNIntoArrayOfMPlusN.java
66 lines (58 loc) · 1.6 KB
/
MergeArrayOfNIntoArrayOfMPlusN.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
package com.rampatra.arrays;
import java.util.Arrays;
/**
* Created by IntelliJ IDEA.
*
* @author rampatra
* @since 7/27/15
* @time: 12:15 PM
*/
public class MergeArrayOfNIntoArrayOfMPlusN {
private static final int NA = -1;
/**
* Move non {@code NA} elements to the end of array leaving everything else unchanged.
* <p/>
* For example,
* Input: {2, NA, 7, NA, NA, 10, NA};
* Output: {2, NA, 7, NA, 2, 7, 10}
*
* @param arrayMPlusN
*/
public static void moveElementsToEnd(int[] arrayMPlusN) {
int i = arrayMPlusN.length - 1, j = i;
for (; i >= 0; i--) {
if (arrayMPlusN[i] != NA) {
arrayMPlusN[j] = arrayMPlusN[i];
j--;
}
}
}
/**
* Merge {@param n} into {@param mPlusN}
*
* @param mPlusN
* @param n
*/
public static void merge(int[] mPlusN, int[] n) {
moveElementsToEnd(mPlusN);
int i = n.length, // current index in mPlusN[]
j = 0, // current index in n[]
k = 0; // current index in final result
while (k < mPlusN.length) {
if (j == n.length || (i < mPlusN.length && mPlusN[i] < n[j])) {
mPlusN[k] = mPlusN[i];
i++;
} else {
mPlusN[k] = n[j];
j++;
}
k++;
}
}
public static void main(String[] args) {
int[] mPlusN = {2, NA, 12, NA, NA, 14, NA};
int[] n = {5, 7, 8, 10};
merge(mPlusN, n);
System.out.println(Arrays.toString(mPlusN));
}
}