-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMergeSortedArrays.java
More file actions
49 lines (48 loc) · 1.26 KB
/
Copy pathMergeSortedArrays.java
File metadata and controls
49 lines (48 loc) · 1.26 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
package Array;
/**
* Created by Prashant on 5/30/16.
* There are two sorted arrays. First one is of size m+n containing only m elements.
* Another one is of size n and contains n elements.
* Merge these two arrays into the first array of size m+n such that the output is sorted.
*/
public class MergeSortedArrays {
static int moveElements(int[] a) {
int size = a.length;
int i = size-1;
int j = size-1;
while(i>=0) {
if(a[i]!=-1) {
a[j] = a[i];
j--;
}
i--;
}
return ++j;
}
static void mergeSortedArray(int[] a, int[] b) {
int i = moveElements(a);
int j = 0;
int k = 0;
while(i<a.length&&j<b.length){
if(a[i]<b[j]) {
a[k++] = a[i++];
} else {
a[k++] = b[j++];
}
}
while(i<a.length) {
a[k++] = a[i++];
}
while(j<b.length){
a[k++] = b[j++];
}
}
public static void main(String[] args) {
int[] a = {2,-1,7,-1,-1,10,-1};
int[] b = {5,8,12,14};
mergeSortedArray(a,b);
for(int i=0;i<a.length;i++){
System.out.print(a[i] + " ");
}
}
}