索引数组快速排序调试

时间:2011-06-22 05:06:08

标签: c++ debugging quicksort

我对这个特殊的快速排序算法感到困惑,我不知道问题出在哪里。我在论坛上找到了一个很好地解释我正在尝试做什么的例子。

  

给定一个连续的索引数组,   有序数字(代表元素   在数据数组中),你仍然需要   比较数据值;你刚才   通过索引访问它们。你交换   但是,索引值不是   数据值。

Unsorted data: 09 04 47 05 03 12
Index array:   00 01 02 03 04 05

After sort,
Unsorted data: 09 04 47 05 03 12
Index array:   04 01 03 00 05 02

Print the values indexed by the index array,
from beginning to end of the array:

Index array [0] value [04] data array [04] = 03
            [1]        01             [01]   04
            [2]        03             [03]   05
            [3]        00             [00]   09
            [4]        05             [05]   12
            [5]        02             [02]   47

Output is the data, ordered at the output

我只添加一件事。比较器是一个普通的比较器,但如果我们将两个不同的字符与相同的值进行比较,我们会比较每个字符的下一个字符并返回该结果。也就是说,比较轮换。

int compare(unsigned char i, unsigned char j);

我不会发布定义,因为我确信它完美无缺。错误在于快速定义。

void quicksort(unsigned char* a, unsigned char left, unsigned char right) {
    unsigned char i = left;
    unsigned char j = right;
    unsigned char half = (left + right) / 2;
    while (i <= j) {
        while ((compare(a[i], a[half]) == -1) && (i < right))
            i++;
        while ((compare(a[j], a[half]) == 1) && (j > left))
            j--;

        if (i <= j) {
            unsigned char aux = a[i];
            a[i] = a[j];
            a[j] = aux;
            i++;       //THERE
            j--;       //THERE
        }

    }

    if (left < j)
        quicksort(a, left, j);
    if (i < right)
        quicksort(a, i, right);

}

有时i = 255且j = 0,我不知道为什么,程序到达THERE,它们的值会溢出。我已经找了一千次虫子,我找不到错误的位置 笔记: 1)我完全了解C ++ unsigned char范围,我不能将它们更改为int。 2)我实际上并没有包含实际数据数组的声明。 compare函数可以访问它,因为它是它的类的属性。

1 个答案:

答案 0 :(得分:1)

呃,你无法在unsigned char中存储大于255或小于0的数字。 unsigned char可以存储由一个无符号字节定义的范围,因此存储8个二进制数字。 2 ^ 8 = 256,因为我们包含0,所以我们有256 - 1,给我们255.(或十六进制,0xFF)

尝试使用整数,甚至是短裤。 (关键字short