我已经完成了MergeSort代码的一部分,但是存在一些比较和交换问题。我设置的temp
向量正在以相同方式将要排序的向量复制到temp
向量中。例如,我要排序的向量将是v={5104, 8199, 123, 5678, 9999, 4356}
,然后在程序结束时,以temp
的相同方式设置temp={5104, 8199, 123, 5678, 9999, 4356}
向量。我拥有所有需要的变量,并被告知在outplaceMerge
方法中不应该有for循环,只有while
和if
/ else
语句不可以。我本来不想发这个问题,但我很茫然。
int main (int argc, char* argv[]) {
//I have a method that makes the vector size its not shown
size_t n = vectorSize();
vector<int> vect(n);
std::random_device sd;
std::mt19937 mt(sd());
std::uniform_int_distribution<int> dist (0, 9999);
for (size_t i = 0; i < n; ++i)
{
vect[i] = dist(mt);
}
mergeSort(vect);
cout << "Merge time: " << ms << endl;
vector<int> ACopy(vect);
std::sort(ACopy.begin(), ACopy.end());
if(vect == ACopy) {
cout << "Merge ok? true" << endl;
}else{
cout << "Merge ok? false" << endl;
}
return EXIT_SUCCESS;
}
/************************************************************/
size_t mergeSortH(vector<int>& v, vector<int>& temp, size_t first, size_t last) {
if (last - first > 1) {
size_t mid = first+(last-first) / 2;
mergeSortH(v, temp, first, mid);
mergeSortH(v, temp, mid, last);
outplaceMerge(v, temp, first, mid, last);
}
//will return numCompares I just am waiting till I fix my sort
return 0;
}
/************************************************************/
size_t outplaceMerge(vector<int>& v, vector<int>& temp, size_t first, size_t mid, size_t last) {
size_t numCompares = 0;
size_t i1 = first;
size_t i2 = mid;
size_t i3 = first;
while((v[first] < mid) && (v[first] < last)) {
if(v[first] < v[mid]) {
temp[i3] = v[i1];
++i1;
} else {
temp[i3] = v[i2];
++i2;
}
++i3;
}
if(i1 > mid) {
while(i2 < last) {
temp[i3] = v[i2];
++i2;
++i3;
}
} else {
while(i1 <= mid){
temp[i3] = v[i1];
++i1;
++i3;
}
}
cout << i3 << endl;
return numCompares;
}
/************************************************************/
size_t mergeSort(vector<int>& v)
{
vector<int> temp(v.size());
return mergeSortH(v, temp, 0, v.size());
}
/************************************************************/
应将向量v={5104, 8199, 123, 5678, 9999, 4356}
排序为temp={123, 4356, 5104, 5678, 8199, 9999}
,然后将这些变量放回原始向量v={123, 4356, 5104, 5678, 8199, 9999}
中。
不需要输出,只需要排序即可,并且随机数gen构成原始向量,因此这些值仅是示例。将Acopy
语句与合并排序完成后进行比较,以显示其是否已排序。如果合并是=到Acopy
,则合并返回true
。