簡體   English   中英

計數排序混亂。 不對數組進行排序(C ++)

[英]Counting Sort confusion. Not sorting array (c++)

我正在研究計數排序,並決定嘗試在網上找到的算法。 雖然,它似乎並沒有真正排序我的數組。

void countSort2(int arr[], int n, int exp)
{
    int *output = new int[n]; // output array
    int i, count[10] = {0};

    // Store count of occurrences in count[]
    for (i = 0; i < n; i++)
        count[ (arr[i]/exp)%10 ]++; 

    // Change count[i] so that count[i] now contains actual position of
    // this digit in output[]
    for (i = 1; i < 10; i++)
        count[i] += count[i - 1];

    // Build the output array
    for (i = n - 1; i >= 0; i--)
    {
        output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
        count[ (arr[i]/exp)%10 ]--;
    }

    // Copy the output array to arr[], so that arr[] now
    // contains sorted numbers according to curent digit
    for (i = 0; i < n; i++)
        arr[i] = output[i];
}

int main()
{
    int b[10] = {4,3,2,1,6,7,8,9,7,6};
    countSort2(b,10,10);
    int i = 0;
    while(i<10)
    {
        cout<<b[i]<<endl;
        i++;
    }

當數組打印出來時,我得到:“ 4,3,2,1,6,7,8,9,7,6”。 我調用該函數是否錯誤?

這就是調用方法[1]的方法。

10是元素數...

int main()
{
   int b[10] = {14,23,22,11,66,67,58,49,17,16};
    countSort2(b,10,1);
    countSort2(b,10,10);

    int i = 0;
    while(i<10)
    {
        cout<<b[i]<<endl;
        i++;
    }
   return 0;
}

這是一個基數排序,按十進制數字對數組排序。 排序是從最低有效位到最高有效位進行的。 這意味着一系列具有exp = 1、10、100、1000、10000 ...的調用。

這是一個基數排序的示例,它按整數中的字節(從最低有效到最高有效)對64位無符號整數數組進行排序。 在此示例中,臨時數組作為參數傳遞給RadixSort():

typedef unsigned __int64    UI64;
typedef unsigned __int64 *  PUI64;

PUI64 RadixSort(PUI64 pData, PUI64 pTemp, size_t count)
{
size_t mIndex[8][256] = {0};            // index matrix
PUI64 pDst, pSrc, pTmp;
size_t i,j,m,n;
UI64 u;

    for(i = 0; i < count; i++){         // generate histograms
        u = pData[i];
        for(j = 0; j < 8; j++){
            mIndex[j][(size_t)(u & 0xff)]++;
            u >>= 8;
        }       
    }
    for(j = 0; j < 8; j++){             // convert to indices
        n = 0;
        for(i = 0; i < 256; i++){
            m = mIndex[j][i];
            mIndex[j][i] = n;
            n += m;
        }       
    }

    pDst = pTemp;                       // radix sort
    pSrc = pData;
    for(j = 0; j < 8; j++){
        for(i = 0; i < count; i++){
            u = pSrc[i];
            m = (size_t)(u >> (j<<3)) & 0xff;
            pDst[mIndex[j][m]++] = u;
        }
        pTmp = pSrc;
        pSrc = pDst;
        pDst = pTmp;
    }

return(pSrc);

}

暫無
暫無

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

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