未处理的异常排序递归

时间:2014-09-24 00:49:45

标签: c++ sorting recursion

我在C ++中遇到递归排序赋值问题。不幸的是,我们已经被指派以非常具体的方式去做,但我似乎无法让它做我想做的事情,而且由于我不习惯递归,我可以'跟着它很好地解决问题。我得到的错误是Unhandled exception at 0x77d915fe in SortFinal.exe: 0xC0000005: Access violation.大概这是从sort函数中使用的a[]数组以某种方式出现的。我是这个网站的新用户,请原谅我,如果组织很糟糕,但这是我现在的代码:

#include <iostream>
using namespace std;
// prototypes
void sort(int a[], int i, int j);

int main() {
    int x[4] = {3, 1, 5, 2};

    for (int count = 0; count < 4; count++) {
        cout << x[count] << ": ";
    }

    cout << endl;

    sort(x, 0, 4);

    for (int count = 0; count < 4; count++) {
        cout << x[count] << ": ";
    }

    cout << endl;

    system("pause");
    return 0;
}

void sort(int a[], int i, int j) {
    int first;
    if (j > i) {
        int index = i + 1;
        bool done = false;
        first = a[i];
        sort(a, i + 1, j);
        for (!done && index <= j; index++;) {
            if (first < a[index]) {

                a[index - 1] = a[index];
            } else {
                a[index - 1] = first;
                done = true;
            }
        }

        if (!done && index > j) {
            a[index - 1] = first;
        }
    }
}

1 个答案:

答案 0 :(得分:3)

有问题的一行是:{for循环中的for (!done && index <= j; index++;) {第一个块是初始化,第二个停止条件,第三个是增量,在你的情况下,你将停止条件作为初始化增加作为停止条件,由for (; !done && index <= j; index++) {更改。在发布SO之前请一定要好好看看。任何编译器(我的意思是ANY)都会捕获此错误,并显示足以让您找出问题的错误消息。在GCC 4.9.1中是:

E:\test.cpp: In function 'void sort(int*, int, int)':
E:\test.cpp:34:20: warning: statement has no effect [-Wunused-value]
         for (!done && index <= j; index++;) {
                    ^

在所有警告启用时编译( -Wall 在GCC和Clang中,在Visual C ++中至少选择 4级),编译器会帮助您修复很多(有效的代码是错误)。