代码改变世界

基数排序-LSD

2017-12-19 23:25  woodzcl  阅读(267)  评论(0编辑  收藏  举报

这个最低位优先的基数排序,非常适合移植到硬件设备中,所以,我们提供一个C源码

——————————————————————————————————————

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

 

#define maxSize 100

#define maxValue 20000

typedef struct

{

    int data;

    int link;

}SLNode;

typedef struct

{

    SLNode elem[maxSize];

    int n;

}StaticLinkList;

 

void createSList(StaticLinkList *SL, int arr[], int n)

{

    for (int i=0; i<n; i++)

    {

        SL->elem[i+1].data = arr[i];

        SL->elem[i+1].link = i+2;

    }

    SL->elem[0].data = maxValue;

    SL->elem[0].link = 1;

    SL->elem[n].link = 0;

    SL->n = n;

}

 

#define rd 10

#define d 3

 

int getDigit(int x, int k)

{

    if (k<1||k>d)

    {

        return -1;

    }

    for(int i=1; i<=d-k; i++)

    {

        x /= 10;

    }

    return x%10;

}

 

void SLinkRadixSort(StaticLinkList * SL)

{

    int front[rd], rear[rd];

    int i, j, k, last, s, t;

 

    for (i=d; i>=1; i--)

    {

        for (j=0; j<rd; j++)

        {

            front[j] = 0;

        }

 

        for (s=SL->elem[0].link; s!=0; s=SL->elem[s].link)

        {

            k = getDigit(SL->elem[s].data, i);

            if (0==front[k])

            {

                front[k] = s;

            }

            else

            {

                SL->elem[rear[k]].link = s;

            }

            rear[k] = s;

        }

 

        for (j=0; j<rd&&0==front[j]; j++);

 

        SL->elem[0].link = front[j];

        last = rear[j];

 

        for (t=j+1; t<rd; t++)

        {

            if (0!=front[t])

            {

                SL->elem[last].link = front[t];

                last = rear[t];

            }

        }

        SL->elem[last].link = 0;

    }

}

 

void main()

{

    int arr[] = {332, 633, 589, 232, 664, 179, 457, 825, 405, 361};

    int len = sizeof(arr)/sizeof(int);

 

    StaticLinkList SL;

    createSList(&SL, arr, len);

    SLinkRadixSort(&SL);

 

    for (int i=SL.elem[0].link; 0!=i; i = SL.elem[i].link)

    {

        printf("%d ", SL.elem[i].data);

    }

 

    printf("\n");

}

//result

# ./sort
179 232 332 361 405 457 589 633 664 825