【问题标题】:C++ Quicksort Seg FaultC++ 快速排序段错误
【发布时间】:2012-05-23 07:22:23
【问题描述】:

我正在尝试修改快速排序算法,并实现一个随机数的枢轴,从而试图避免 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() % range) 来钳制随机数...
  • 你使用的是哪个调试器?

标签: c++ algorithm segmentation-fault quicksort


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-17
    • 2017-04-17
    • 2018-11-06
    • 2017-06-20
    • 2017-11-04
    • 2021-10-01
    • 1970-01-01
    • 2016-06-04
    相关资源
    最近更新 更多