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