首页 > 解决方案 > 尽管没有错误并且完全执行,但 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

标签: c++sortingrecursionquicksort

解决方案


这段代码:

    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];

这也会导致您出现未定义的行为。


推荐阅读