简体   繁体   中英

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++.

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

There were problems in both functions:

partition():

  • first swap had wrong arguments.
  • second swap had to be moved out of the for-loop (suggested by Faruk Hossain)
  • if (vec[j] < vec[r-1]) became if (vec[j] <= vec[r-1])

sortVector():

  • if (pr<1) became if (p<r)

Working code below.

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[i], vec[j]);
            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 (r>p) {
        int q = partition(vec, p, r);
        sortVector(vec, p, q);
        sortVector(vec, q+1, r);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM