-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSortedArray.java
More file actions
38 lines (32 loc) · 871 Bytes
/
MergeSortedArray.java
File metadata and controls
38 lines (32 loc) · 871 Bytes
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
public class MergeSortedArray {
public static void main(String[] args) {
int[] nums1 = {1,2,3,0,0,0};
int m = 3;
int[] nums2 = {2,5,6};
int n = 3;
merge(nums1, m, nums2, n);
for(int num : nums1){
System.out.print(num + " ");
}
}
public static void merge(int[] nums1, int m, int[] nums2, int n) {
int i = m - 1; // nums1 last element
int j = n - 1; // nums2 last element
int k = m + n - 1; // last position
while(i >= 0 && j >= 0){
if(nums1[i] > nums2[j]){
nums1[k] = nums1[i];
i--;
} else {
nums1[k] = nums2[j];
j--;
}
k--;
}
while(j >= 0){
nums1[k] = nums2[j];
j--;
k--;
}
}
}