我目前正在学习算法的分而治之策略,并认为“合并排序”是一个很好的示例,演示了该策略。
我在彻底理解该概念时遇到了一些麻烦,因此我决定尝试自己实施它。我尝试了一下,我想知道这是Merge Sort的正确实现。
vector<int> mergeSort(vector<int> n) {
if(n.size() == 1) {
return n;
} else if(n.size() == 2) {
vector<int> newVector;
newVector.reserve(2);
if(n[0] < n[1]) {
newVector.push_back(n[0]);
newVector.push_back(n[1]);
} else {
newVector.push_back(n[1]);
newVector.push_back(n[0]);
}
return newVector;
} else {
int endIndexLeft = floor(n.size() / 2);
int startIndexRight = ceil(n.size() / 2);
vector<int>::const_iterator first = n.begin();
// divide into 2 vectors
vector<int> L(first, first + endIndexLeft + 1);
vector<int> R(first + endIndexLeft + 1, first + n.size());
// recursive call on each
L = mergeSort(L);
R = mergeSort(R);
// combine the resulting array accordingly
vector<int> sorted;
sorted.reserve(n.size());
int index_l = 0, index_r = 0;
for(int i=0; i<n.size(); i++) {
if(index_l == L.size()) {
sorted.push_back(R[index_r]);
index_r++;
} else if(index_r == R.size()) {
sorted.push_back(L[index_l]);
index_l++;
} else if(L[index_l] < R[index_r]) {
sorted.push_back(L[index_l]);
index_l++;
} else {
sorted.push_back(R[index_r]);
index_r++;
}
}
return sorted;
}
}
经过一些测试,似乎它会生成正确的输出(按升序排列的矢量),但我不确定该实现是否显示了分治策略的使用。提前致谢!
[编辑:意识到我什至不需要n.size() == 2
部分,因此我摆脱了这一点,并分离出合并功能。]
vector<int> mergeVector(vector<int> L, vector<int> R) {
vector<int> combined;
combined.reserve(L.size() + R.size());
int index_l = 0, index_r = 0;
for(int i=0; i<L.size() + R.size(); i++) {
if(index_l == L.size()) {
combined.push_back(R[index_r]);
index_r++;
} else if(index_r == R.size()) {
combined.push_back(L[index_l]);
index_l++;
} else if(L[index_l] < R[index_r]) {
combined.push_back(L[index_l]);
index_l++;
} else {
combined.push_back(R[index_r]);
index_r++;
}
}
return combined;
}
vector<int> mergeSort(vector<int> n) {
if(n.size() == 1) {
return n;
} else {
int endIndexLeft = floor(n.size() / 2);
vector<int>::const_iterator first = n.begin();
// divide into 2 vectors
vector<int> L(first, first + endIndexLeft);
vector<int> R(first + endIndexLeft, first + n.size());
// recursive call on each
L = mergeSort(L);
R = mergeSort(R);
// combine the resulting arrays
vector<int> sorted;
sorted.reserve(n.size());
sorted = mergeVector(L,R);
return sorted;
}
}