-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeshort.cpp
More file actions
48 lines (38 loc) · 879 Bytes
/
mergeshort.cpp
File metadata and controls
48 lines (38 loc) · 879 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
39
40
41
42
43
44
45
46
47
48
#include <iostream>
#include <vector>
#include <climits>
void merge(std::vector<int>& A, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
std::vector<int> L(n1 + 1);
std::vector<int> R(n2 + 1);
for (int i = 0; i < n1; ++i) {
L[i] = A[p + i];
}
for (int j = 0; j < n2; ++j) {
R[j] = A[q + 1 + j];
}
L[n1] = INT_MAX;
R[n2] = INT_MAX;
int i = 0, j = 0;
for (int k = p; k <= r; ++k) {
if (L[i] <= R[j]) {
A[k] = L[i];
i++;
} else {
A[k] = R[j];
j++;
}
}
}
int main() {
std::vector<int> A = {3, 7, 12, 18, 5, 8, 15, 17};
int p = 0, q = 3, r = 7;
merge(A, p, q, r);
std::cout << "Merged array: ";
for (int num : A) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}