C++ Quicksort Seg Fault

Edg*_*dge 0 c++ algorithm quicksort segmentation-fault

我正在尝试修改快速排序算法,并实现一个随机数的轴,从而试图避免O(n ^ 2)问题.我想使用随机数,但我的代码给出了分段错误.

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;
}
Run Code Online (Sandbox Code Playgroud)

NPE*_*NPE 5

您的random()函数生成的值超出范围,而不是其中:

int random (int num) {
    int random = rand();
    while (random > 1 && random < num - 1) {
        random = rand();
    }
    return random;
}
Run Code Online (Sandbox Code Playgroud)

partition()当它试图取消引用越界元素时,这将导致段错误.

我的建议是重写random(),并完全避免循环(如果范围很小,循环可能非常昂贵).