0

I'm having an issue with a recursive sorting assignment in C++. Unfortunately, we've been assigned to do it in a very specific way, but I cannot seem to manage to get it to do what I want, and since I'm not used to recursion, I can't follow it well to trouble shoot. The error that I'm getting is Unhandled exception at 0x77d915fe in SortFinal.exe: 0xC0000005: Access violation. Presumably this is coming somehow from the a[] array used within the sort function. I'm new to this site so forgive me if the organization is terrible, but here's my code as it currently stands:

#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 Answer 1

3

The line with the problem is: for (!done && index <= j; index++;) { in the for loop the first block is initialization, the second stop condition and the third is increment, in you case you are putting stop condition as initialization and increment as stop condition, changed by for (; !done && index <= j; index++) {. Please take always good look before posting in SO. Any compiler (and I mean ANY) would catch this error with a error message good enough for you to figure out the problem. In GCC 4.9.1 was:

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++;) {
                    ^

Compile always with all warnings enable (-Wall in GCC and Clang, select at least level 4 in Visual C++), the compiler would help you to fix a lot (valid code that are bugs).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I feel incredibly dumb. I'll be more careful next time before posting.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.