Edge
Edge

Reputation: 2540

C++ Quicksort Seg Fault

I'm attempting to modify a quicksort algorithm, and implement a pivot that is a random number, thus attempting to avoid the O(n^2) issue. I'd like to use a random number, but my code gives a segmentation fault.

int random (int num) {
    int random = rand() % (num - 1);
    return random;
}

int* partition (int* first, int* last);
void quickSort(int* first, int* last) {
    if (last - first <= 1) return;

    int* pivot = partition(first, last);
    quickSort(first, pivot);
    quickSort(pivot + 1, last);
}

int* partition (int* first, int* last) {   
    int* pos = (first + random(last - first));
    int pivot = *pos;
    int* i = first;
    int* j = last - 1;

    for (;;) {
        while (*i < pivot && i < last) i++;
        while (*j >= pivot && j > first) j--;
        if (i >= j) break;
        swap (*i, *j);
    }
    swap (pos, i);
    return i;
}

Upvotes: 0

Views: 357

Answers (1)

NPE
NPE

Reputation: 500167

Your random() function generates values outside the range, not inside it:

int random (int num) {
    int random = rand();
    while (random > 1 && random < num - 1) {
        random = rand();
    }
    return random;
}

This would cause partition() to segfault when it tries to dereference an out-of-bounds element.

My advice would be to rewrite random(), and avoid the loop altogether (the loop can be very expensive if the range is small).

Upvotes: 5

Related Questions