基数排序(静态链表法)

/**
 * author:      bbird_gl
 * date:        2019/7/16
 * description: 基排序(静态链表法实现)
 */
typedef struct {
    int key;    //节点的关键码值
    int next;   //下一个节点在数组中的下标
}Node;

//静态队列
typedef struct {
    int head;
    int tail;
}StaticQueue;

//分配函数
void Distribute(Node arr[], int first, int i, int r, StaticQueue *queue)
{
    for (int j = 0; j < r; j++)
        queue[j].head = -1;

    while (first != -1)     //对整个静态链分配
    {
        int k = arr[first].key;
        for (int a = 0; a < i; a++)
            k = k / r;
        k = k % r;

        if (queue[k].head == -1)
            queue[k].head = first;
        else
            arr[queue[k].tail].next = first;
        queue[k].tail = first;
        first = arr[first].next;
    }
}

//收集函数
void Collect(Node arr[], int *first, int i, int r, StaticQueue *queue)
{
    int last;
    int k = 0;
    while (queue[k].head == -1)
        k++;

    *first = queue[k].head;
    last = queue[k].tail;
    while (k < r - 1)
    {
        k++;
        while (k < r - 1 && queue[k].head == -1)
            k++;
        if (queue[k].head != -1)
        {
            arr[last].next = queue[k].head;
            last = queue[k].tail;
        }
    }
    arr[last].next = -1;
}

//n为数组大小,d为排序码数, r为基数
void RadixSort(int arr[], int n, int d, int r)
{
    Node *list = (Node *)malloc(n * sizeof(Node));    //数组的静态链表
    StaticQueue *queue = (StaticQueue *)malloc(r * sizeof(StaticQueue));
    int first = 0;  //指向静态链中第一个记录

    //初始化静态链表
    for (int i = 0; i < n; i++)
    {
        list[i].next = i + 1;
        list[i].key = arr[i];
    }
    list[n - 1].next = -1;

    //对第j个排序码进行分配和收集,一共d趟
    for (int j = 0; j < d; j++)
    {
        Distribute(list, first, j, r, queue);
        Collect(list, &first, j, r, queue);
    }

    for (int k = 0; k < n && first != -1; k++)
    {
        arr[k] = list[first].key;
        first = list[first].next;
    }

    free(list);
    free(queue);
}

 

你可能感兴趣的:(C语言,数据结构与算法)