c++ - 尽管没有错误并且完全执行,但 C++ 程序中没有输出
问题描述
我在 C++ 中编写了以下递归程序,以使用 QuickSort 算法对数组进行排序,但是尽管程序执行已完成,但我没有得到任何输出(虽然由于 cout,我应该将输出作为空格分隔的数组接收)。
我对 C++(不是编程)相对较新,并且无法找到任何具体的问题。
请帮忙!!
代码:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int partition(int a[], int low, int high)
{
int pivot = a[high];
int x = low;
int y = high;
while (x < y)
{
do
{
x++;
} while (a[x] <= pivot);
do
{
y--;
} while (a[y] > pivot);
a[x] = a[x] + a[y];
a[y] = a[x] - a[y];
a[x] = a[x] - a[y];
}
a[x] = a[x] + a[high];
a[high] = a[x] - a[high];
a[x] = a[x] - a[high];
return x;
}
void quickSort(int a[], int low, int high)
{
if (low < high)
{
int new_limit = partition(a, low, high);
quickSort(a, low, new_limit);
quickSort(a, new_limit + 1, high);
}
}
int main()
{
int n;
int a[1001];
cin >> n;
for (int i = 1; i <= n; ++i)
{
cin >> a[i];
}
a[0] = -1001;
quickSort(a, 0, n);
for (int i = 1; i <= n; ++i)
{
cout << a[i] << " ";
}
return 0;
}
放置随机 cout 语句,只有在快速排序函数中递归快速排序调用之前的语句才会返回输出。
我的输入:
7
8 7 14 6 98 5 4
解决方案
这段代码:
do
{
x++;
} while (a[x] <= pivot);
do
{
y--;
} while (a[y] > pivot);
要去月球和回来。您没有以任何方式检查边界。一旦您尝试使用这些索引写入数组,就会破坏堆栈。
这个数组:
int a[1001];
未初始化。因此,它将填充未定义的数据,这可能会转换为强制转换为大于 x 的整数。
最后但并非最不重要的:
quickSort(a, 0, n);
您将 n (数组的大小)作为 传递high
,但您high
用于索引数组。
这里:
int pivot = a[high];
和这里:
a[high] = a[x] - a[high];
这也会导致您出现未定义的行为。
推荐阅读
- node.js - 启动应用程序时节点模块错误
- sql - Powershell脚本查找行终止符?
- c# - 写入文件跳过最后 10-20 行
- shopify - 我们可以使用店面 GQL API 按重量过滤 shopify 产品吗?
- javascript - 我如何进一步自定义我的反应路由器 dom NavLink activeStyle
- php - 在 php mysql 中从数据库中获取时更改日期格式
- c++ - compact form of many for loop in C++
- c# - 如何在 asp.net mvc 4.5 中预加载包
- vuetify.js - v1.3.x 版本 vuetify 组件 v-treeview 的 API 文档
- javascript - 需要时获得不需要的base64('image.dir')