#include <iostream>
#include <vector>
using namespace std;
void MergeSort(vector<int> &vec, int p, int r);
void Merge(vector<int> &vec, int p, int q, int r);
int main() {
vector<int> A = { 5, 2, 4, 7, 1, 3, 2, 6 };
int p = 0, r = 7;
MergeSort(A, p, r);
for (auto c : A)
cout << c << endl;
return 0;
}
void MergeSort(vector<int> &vec, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
MergeSort(vec, p, q);
MergeSort(vec, q + 1, r);
Merge(vec, p, q, r);
}
}
// Merge函数使用INT_MAX作为哨兵
void Merge(vector<int> &vec, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
vector<int> L(n1 + 1, 0);
vector<int> R(n2 + 1, 0);
for (int i = 0; i != L.size() - 1; ++i) {
L[i] = vec[p + i];
}
for (int i = 0; i != R.size() - 1; ++i) {
R[i] = vec[q + i + 1];
}
L[n1] = INT_MAX;
R[n2] = INT_MAX;
int i = 0;
int j = 0;
int k = p;
while (k != r + 1) {
if (L[i] <= R[j]) {
vec[k] = L[i];
i = i + 1;
}
else {
vec[k] = R[j];
j = j + 1;
}
k++;
}
}
// 不使用哨兵的Merge函数
void Merge(vector<int> &vec, int p, int q, int r) {
int n1 = q - p + 1;
int n2 = r - q;
vector<int> L(n1, 0);
vector<int> R(n2, 0);
for (int i = 0; i != L.size(); ++i) {
L[i] = vec[p + i];
}
for (int i = 0; i != R.size(); ++i) {
R[i] = vec[q + i + 1];
}
int i = 0;
int j = 0;
int k = p;
while (i != L.size() && j != R.size()) {
if (L[i] <= R[j]) {
vec[k] = L[i];
i = i + 1;
}
else {
vec[k] = R[j];
j = j + 1;
}
k++;
}
if (i == L.size()) {
while (j != R.size()) {
vec[k] = R[j];
++j;
++k;
}
}
if (j == R.size()) {
while (i != L.size()) {
vec[k] = L[i];
++i;
++k;
}
}
}
#include <iostream>#include <vector>using namespace std;void MergeSort(vector<int> &vec, int p, int r);void Merge(vector<int> &vec, int p, int q, int r);int mai...