【发布时间】:2017-04-07 20:30:59
【问题描述】:
我正在尝试编写一个使用合并算法对用户输入数组进行排序的 C++ 程序。
分割函数如下:
void split(int numbers[], int size) {
if (size == 1)
return;
int mid = size / 2;
int firstPartSize = mid;
int secondPartSize = size - mid;
int *firstArray;
firstArray = new int[firstPartSize];
int *secondArray;
secondArray = new int[secondPartSize];
for (int i = 0; i < size; i++) {
if (i < mid)
firstArray[i] = numbers[i];
else
secondArray[i - mid] = numbers[i];
}
split(firstArray, firstPartSize);
split(secondArray, secondPartSize);
merge(numbers, firstArray, firstPartSize, secondArray, secondPartSize);
}
合并函数如下:
void merge(int outputArray[], int firstArray[], int n1, int secondArray[], int n2) {
int k = 0;
int i = 0;
int j = 0;
while (i < n1 && j < n2) {
if (firstArray[i] < secondArray[j])
outputArray[k++] = firstArray[i++];
else
outputArray[k++] = secondArray[j++];
}
while (i < n1)
outputArray[k++] = firstArray[i++];
while (j < n2)
outputArray[k++] = secondArray[j++];
for (int c = 0; c < n1+n2; c++)
{
cout << outputArray[c] << " ";
}
}
当我尝试插入一个数组时,这就是我得到的结果
Enter the size of the array you want to sort:
3
Enter the elements of the array:
4
7
1
1 7 1 4 7 Press any key to continue
我在这里错过了什么?
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用调试器来逐步执行代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
sizeof 并没有按照你的想法去做。
-
@MarcoAtef 你读过我给你的链接,关于
sizeof的实际作用吗?它不为您提供数组的大小。除此之外,您是否按照建议尝试使用调试器? -
@MarcoAtef 再一次,在哪里?我看不到你对这个问题的更新。