-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathMergeSortedArray.cpp
33 lines (30 loc) · 932 Bytes
/
MergeSortedArray.cpp
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
class Solution {
public:
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
int gap = ceil((float)(n + m)/2);
while(gap > 0) {
int i = 0;
int j = gap;
while(j < (n+m)) {
if(j < m && nums1[i] > nums1[j])
swap(nums1[i], nums1[j]);
else if (j >= m && i < m && nums1[i] > nums2[j-m])
swap(nums1[i], nums2[j-m]);
else if (j>=m && i >= m && nums2[i-m] > nums2[j-m])
swap(nums2[i-m], nums2[j-m]);
j++;
i++;
}
if(gap == 1) {
gap = 0;
} else {
gap = ceil((float) gap / 2);
}
}
int k = 0;
for(int i = m; i<m+n; i++) {
nums1[i] = nums2[k];
k++;
}
}
};