在C 中合并排序算法
merge sort algorithm in C++
我正在尝试编写一个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
我在这里缺少什么?
代码总体上是正确的,并且一个简单的错误。您正在以递归步骤之一打印输出,因此将中间结果与答案混合在一起。
在merge
功能中删除cout
并将其移出到main
功能将有能力:
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++];
}
int main(int argc, char *argv[]) {
int a[] = {1, 4, 7};
int n = sizeof(a) / sizeof(int);
split(a, n);
cout << "The array is:n";
for (int i = 0; i < n; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
输出:
The array is:
1 4 7
相关文章:
- C++选择排序算法中的逻辑错误
- 排序算法c++
- 下面是排序算法O(n)吗
- 为什么我的排序算法会更改数组值
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 排序算法问题(购买商店物品)(崩溃)
- 为什么这个选择排序算法仍然切换一个元素,当它已经是其他元素中最小的元素时?
- 为什么在此排序算法实现中,向量明显比数组慢?
- C++中合并排序算法的奇怪行为
- 我的排序算法程序中的堆错误
- 如何使用cpp编写选择排序算法以降序对元素列表进行排序?
- 解释一下这个排序算法是如何工作的?
- 快速排序函数在快速排序算法中如何工作?
- 分段故障,合并排序算法
- 这种排序算法已经存在吗?
- 为什么此代码上的排序算法不调用类的交换版本?
- 为什么我的替代排序算法不起作用?
- 选择排序算法生成无序结果
- 递归合并排序算法实现
- 这种快速排序算法有什么问题?