快速排序失败,出现OOB错误

时间:2012-10-24 18:02:32

标签: c++ quicksort

我有一个QuickSort的实现,它失败了索引越界错误,我无法弄清楚原因。

unsigned long PerformQuickSort(std::vector<unsigned int>& values) {
    unsigned long comparisons = 0;
    QuickSortJoiner(values, 0, values.size() - 1, comparisons);
    return comparisons;
}

void QuickSortJoiner(std::vector<unsigned int>& values, std::size_t first, std::size_t last, unsigned long& comparisons) {

    if(first >= last) return;

    std::size_t pivot = first + (last - first) / 2;
    std::size_t newPivot = QuickSortPartitioner(values, first, last, pivot, comparisons);
    QuickSortJoiner(values, first, newPivot - 1, comparisons);
    QuickSortJoiner(values, newPivot + 1, last, comparisons);

}

std::size_t QuickSortPartitioner(std::vector<unsigned int>& values, std::size_t first, std::size_t last, std::size_t pivot, unsigned long& comparisons) {
    unsigned int value = values[pivot];
    Swap(values[pivot], values[last]);
    std::size_t storeAt = first;
    for(std::size_t i = first; i < last; ++i) {
        ++comparisons;
        if(values[i] < value) {
            Swap(values[i], values[storeAt]);
            ++storeAt;
        }
    }
    Swap(values[storeAt], values[last]);
    return storeAt;
}

1 个答案:

答案 0 :(得分:2)

newPivot变为0时,下一次使用无符号类型的newPivot - 1调用将溢出到最大值。在newPivot == 0

之后查看QuickSortPartitioner