0

我正在尝试修改快速排序算法,并实现一个随机数的枢轴,从而试图避免 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;
}
4

1 回答 1

5

您的random()函数生成范围之外的值,而不是范围的值:

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

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

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

于 2012-05-23T07:25:41.537 回答