簡體   English   中英

索引數組快速排序調試

[英]Indexed array quicksort debug

我對這種特殊的快速排序算法很不滿意,我不知道問題出在哪里。 我在一個論壇上找到了一個例子,很好地解釋了我要做什么。

給定一個連續的,有序的數字的索引數組(表示數據數組中的元素),您仍然必須比較數據值。 您只需通過索引訪問它們。 您交換索引值,但是不交換數據值。

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);

我不會發布該定義,因為我確信它可以完美工作。 錯誤在於quicksort定義。

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,但我不為什么,程序到達那里,並且它們的值溢出。 我已經尋找了上千次錯誤,但是我找不到錯誤在哪里。
注意:1)我完全了解C ++無符號字符范圍,並且無法將它們更改為int。 2)我實際上並不包括實際數據數組的聲明。 比較函數可以訪問它,因為它是其類的一個屬性。

不能在無符號字符中存儲大於255或小於0的數字。 一個無符號字符可以存儲一個無符號字節定義的范圍,因此可以存儲8個二進制數字。 2 ^ 8 = 256,由於我們包括0,所以我們有256-1,即為255。(或十六進制為0xFF)

嘗試使用整數,甚至短褲。 (關鍵字short

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM