繁体   English   中英

C ++ Quicksort段故障

[英]C++ Quicksort Seg 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;
}

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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