【发布时间】:2016-02-21 21:55:58
【问题描述】:
大家好,我需要在 C++ 中使用给定的 mergeSort() 标头编写合并排序;
我的分区是正确的,但它合并了一个在它有 0 之前合并的数组。例如:如果我有 [34][21] 我得到 [21, 34] 但是当它与假设 [8] 合并时它给出 [0, 0, 8]。我正在失去价值。请帮我调试一下。
注意: 我有一些 moveCount 来计算数据移动和 compCount 来计算计算。请不要与这些混淆。
int * merge(int * left ,int szLeft ,int * right,int szRight, int &compCount, int &moveCount){
int * newArr = new int [szLeft+szRight];
cout << "Left: ";
for (int i = 0; i < szLeft; ++i){
cout << left[i] << " ";
}
cout << endl;
cout << "Right: ";
for (int i = 0; i < szRight; ++i){
cout << right[i] << " ";
}
cout << endl;
int bigArrIndex = 0, rightArrIndex = 0,leftArrIndex = 0;
while(leftArrIndex < szLeft && rightArrIndex < szRight){
compCount++;
if(right[rightArrIndex] <= left[leftArrIndex]){
newArr[bigArrIndex] = right[rightArrIndex];
rightArrIndex++;
compCount++;
}
else{
newArr[bigArrIndex] = left[leftArrIndex];
leftArrIndex++;
}
moveCount++;
bigArrIndex++;
}
//1 more computation done even if the loop is not executed
compCount++;
//copy the rest of the stuff if left
while(rightArrIndex < szRight){
moveCount++;
compCount++;
newArr[bigArrIndex] = right[rightArrIndex];
rightArrIndex++;
bigArrIndex++;
}
//1 more computation done even if the loop is not executed
compCount++;
//copy the rest of the stuff if left
while(leftArrIndex < szLeft){
moveCount++;
compCount++;
newArr[bigArrIndex] = left[leftArrIndex];
leftArrIndex++;
bigArrIndex++;
}
//1 more computation done even if the loop is not executed
compCount++;
return newArr;
}
void mergeSort( int * arr, int size, int &compCount, int &moveCount){
//to take the branch or not needs 1 comparison
compCount++;
if(size > 1){
int mid = size/2;
int * left = new int[mid];
int * right = new int[size-mid];
for(int i = 0; i < mid; i++){
compCount++;
left[i] = arr[i];
moveCount++;
}
//1 more computation done even if the loop is not executed
compCount++;
for(int i = mid; i < size; i++){
right[i-mid] = arr[i];
moveCount++;
compCount++;
}
//1 more computation done even if the loop is not executed
compCount++;
mergeSort(left,mid,compCount,moveCount);
mergeSort(right,size-mid,compCount,moveCount);
int * sortedArr = merge(left,mid,right,size-mid,compCount,moveCount);
cout << "Done: ";
for (int i = 0; i < size; ++i)
cout << sortedArr[i] << " ";
cout << endl;
//delete[] left;
//delete[] right;
for(int i = 0; i < size; i++){
arr[i] = sortedArr[size];
moveCount++;
compCount++;
}
//1 more computation done even if the loop is not executed
compCount++;
}
}
【问题讨论】:
-
请帮我调试一下。 -- 使用编译器自带的调试器。
-
@PaulMcKenzie 我不知道如何使用 gdb。我正在使用 g++ 编译器
-
好了,现在是学习使用调试器的好时机。编程不仅仅是写代码、运行代码,如果有问题,去SO寻求帮助。学习如何调试代码是学习如何编写程序的一部分。
-
@PaulMcKenzie 我没有多少时间了,我正在尝试调试它。哈哈。我没有懈怠。但头脑越多越好。
标签: c++ sorting merge mergesort