我正在练习合并排序(用于面试准备)。我遇到了一个非常奇怪的向量问题。似乎将某个值推回到向量上并不会导致该值实际放在那里。我可能会遗漏一些明显的东西,但我不确定。以下是合并排序的代码(添加了一些打印语句以了解出现了什么问题)
void merge(std::vector<int> *vec, int low, int middle, int high) {
printf("Entering Merge(%d, %d, %d)\n", low, middle, high);
std::vector<int> helper;
for(int i = low; i <= high; ++i) {
helper.push_back( (*vec)[i] );
}
std::cout << "Array being worked on: [";
for(auto &p : helper) {
std::cout << p << ", ";
} std::cout << "]" << std::endl;
int helperLeft = low, helperRight = middle + 1, vecIndex = low;
while(helperLeft <= middle && helperRight <= high) {
if(helper[helperLeft] <= helper[helperRight]) {
(*vec)[vecIndex] = helper[helperLeft];
++helperLeft;
std::cout << "Helper Left: " << helperLeft << std::endl;
}
else {
(*vec)[vecIndex] = helper[helperRight];
++helperRight;
std::cout << "Helper Right: " << helperRight << std::endl;
}
++vecIndex;
std::cout << "Current Index: " << vecIndex << std::endl;
}
// Copy over the remaining elements into the array
while(helperLeft <= middle) {
std::cout << "Entered Left Remaining" << std::endl;
(*vec)[vecIndex] = helper[helperLeft];
++helperLeft;
++vecIndex;
}
while(helperRight <= high) {
std::cout << "Entered Right Remaining" << std::endl;
(*vec)[vecIndex] = helper[helperRight];
++helperRight;
++vecIndex;
}
std::cout << "Resulting Array: [";
for(int i = low; i < high; ++i) {
std::cout << (*vec)[i] << ", ";
} std::cout << (*vec)[high] << "]" << std::endl;
std::cout << std::endl;
}
void mergeSort(std::vector<int> *vec, int low, int high) {
if(low < high) {
int middle = (low + high) / 2;
mergeSort(vec, low, middle);
mergeSort(vec, middle + 1, high);
merge(vec, low, middle, high);
}
}
int main() {
std::vector<int> array({2, 25, 1, 1, 5});
mergeSort(&array, 0, array.size() - 1);
}