所以我试图编写代码来对向量进行合并排序工作。然而,我现在遇到一个问题,即每当我输入矢量大小的大小不是2的幂时,最终的排序矢量将其大小向下舍入到最接近的2的幂。如果矢量大小设置为10,它将返回8,如果它是100,它将返回64.我不知道为什么会这样。这是代码:
#include <iostream>
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
#include <vector>
#include <assert.h>
#include <iterator>
#include <algorithm>
#include <functional>
using namespace std;
vector<int> merge(vector<int> &left, vector<int> &right) {
vector <int> result;
while (left.size() > 0 && right.size()>0) {
if (left[0] <= right[0]) {
result.push_back(left[0]);
left.erase(left.begin());
}
else {
result.push_back(right[0]);
right.erase(right.begin());
}
}
if (left.size() > 0) {
result.insert(result.end(), left.begin(), left.end());
}
if (right.size() > 0) {
result.insert(result.end(), right.begin(), right.end());
}
return result;
}
vector <int> mergesort(vector < int > &vector_sort) {
int size_of = vector_sort.size() / 2;
vector <int > left(size_of), right(size_of), result(vector_sort.size());
if (vector_sort.size() <= 1) {
return vector_sort;
}
else {
int middle = vector_sort.size() / 2;
int counter = middle;
int second_half = middle;
for (int i = 0; i < middle; i++) {
left[i] = vector_sort[i];
}
for (int i = 0; i < middle; i++) {
right[i] = vector_sort[counter];
counter++;
}
left = mergesort(left);
right = mergesort(right);
if (left.back() <= right[0]) {
left.insert(left.end(), right.begin(), right.end());
return left;
}
result = merge(left, right);
return result;
}
}
int main() {
const int t=10;
vector<int> vector_no(t);
vector<int> empty(t);
for (int i = 0; i < t; i++) {
int hello = rand() % 100000 + 1;
vector_no[i] = hello;
}
int hello2 = 0;
for (int i = 0; i < vector_no.size(); i++) {
hello2++; //I am using this for loop here just to count the size of the vector without getting a stack overflow error
}
cout << hello2 << "\n";
vector_no = mergesort(vector_no);
hello2 = 0;
for (int i = 0; i < vector_no.size(); i++) {
hello2++; //I am using this for loop here just to count the size of the vector without getting a stack overflow error
}
cout << hello2 << "\n";
}
答案 0 :(得分:2)
当你构造右向量时,你应该添加一些等于middle的元素,当你应该添加vector_sort.size() - 元素元素的中间数。因为除法向下舍入,这会导致您删除奇数长度的列表上的最后一个元素。并且因为您将向下排序合并为0或1个元素,所以它会使结果为2的幂。