Quicksort算法访问违规写入位置

时间:2017-03-10 03:02:45

标签: c++ visual-studio quicksort access-violation

以下快速排序算法的实施有什么问题。调试报告"访问违规写入位置"。我无法找到它。我应该将枢轴的位置作为参数传递给sortpartition函数吗?此代码基于此互动在线演示:http://me.dt.in.th/page/Quicksort

#include <cstdio>
#include <cstdlib>
#include <cstdint>
#include <utility>

#define LIST_SIZE (UInt)10

typedef uint64_t UInt;

void print(UInt * list, UInt size) {
    for (UInt i = 0; i < size; i++)
        printf("%llu ", list[i]);

    printf("\n");
}

void fill(UInt * list, UInt size) {
    for (UInt i = 0; i < size; i++)
        list[i] = (UInt)std::rand();
}

UInt partition(UInt * list, UInt left, UInt right) {
    UInt p = list[left], t = left + 1;

    for (UInt i = left + 1; i <= right; i++) {
        if (list[i] < p) {
            std::swap(list[i], list[t]);
            t++;
        }
    }

    std::swap(p, list[t]);

    return t;
}

void sort(UInt * list, UInt left, UInt right) {
    UInt p;

    if (left < right) {
        p = partition(list, left, right);

        sort(list, left, p - 1);
        sort(list, p + 1, right);
    }
}

void quicksort(UInt * list, UInt size) {
    sort(list, 0, size - 1);
}

int main(int argc, char ** argv) {
    UInt list[LIST_SIZE];

    fill(list, LIST_SIZE);
    print(list, LIST_SIZE);
    quicksort(list, LIST_SIZE);
    print(list, LIST_SIZE);

    return 0;
}

1 个答案:

答案 0 :(得分:1)

以下更改为您提供了诀窍。在for循环中,你必须检查i&lt;对。如果你做了&lt; =那里,你在某些情况下不会取得进展。但是,我现在没有检查你的算法是否在各方面都是正确的。

UInt partition(UInt * list, UInt left, UInt right) {
    UInt p = list[left], t = left + 1;

    for (UInt i = left + 1; i < right; i++) {
        if (list[i] < p) {
            std::swap(list[i], list[t]);
            t++;
        }
    }

    std::swap(p, list[t]);

    return t;
}