Search code examples
c++sortingquicksortexc-bad-accessstdvector

Quicksort in C++ with std::vector, EXC_BAD_ACCESS code 2


VS Code catches this exception when I run my quicksort algorithm: EXC_BAD_ACCESS (code=2, address=0x7ffeef3ffffc). This happens on the first line in partition():

int i = p;

I have tried to implement the Cormen algorithm: http://www.cs.fsu.edu/~lacher/courses/COP4531/lectures/sorts/slide09.html

Why can I not access the variable p? Is it released, and if so, how do I fix this?

My code

//.h file
void sortVector(vector<int> &vec, int p=0, int r=-2);
int partition(vector<int> &vec, int p, int r);

//.cpp file
int partition(vector<int> &vec, int p, int r) {
    int i = p;
    for (int j = p; j <r-1; ++j) {
        if (vec[j] < vec[r-1]) {
            swap(vec[j], vec[r-1]);
            i++;
        }
        swap(vec[i], vec[r-1]);
    }
    return i;
}

void sortVector(vector<int> &vec, int p, int r) {
    if (r == -2) {
        r = vec.size();
    }
    if (p-r<1) {
        int q = partition(vec, p, r);
        sortVector(vec, p, q);
        sortVector(vec, q+1, r);
    }

}

I am including "std_lib_facilities.h" from Stroustrup: Programming Principles and Practice Using C++.


Solution

  • You need to write swap(vec[i], vec[r-1]); out of for loop.

    It should be like this -

    //.cpp file
    int partition(vector<int> &vec, int p, int r) {
        int i = p;
        for (int j = p; j <r-1; ++j) {
            if (vec[j] < vec[r-1]) {
                swap(vec[j], vec[r-1]);
                i++;
            }
        }
        swap(vec[i], vec[r-1]);
    
        return i;
    }