基数排序(基于分配和收集的排序)纯C代码

#include <stdio.h>
#define MaxSize 12  // 循环队列容量+2(fron和rear指向不存储数据)

typedef struct Queue
{
    int data[MaxSize];
    int fron, rear;
} Queue;

void InitQueue(Queue *q)
{
    q->fron = 0;
    q->rear = 1;
}

void EnQueue(Queue *q, int e)
{
    if((q->fron == q->rear + 1) || (q->fron == (q->rear + 1) % MaxSize))
    {
        printf("\nFULL_ERROR");
        return;
    }
    q->data[q->rear] = e;
    q->rear = (q->rear + 1) % MaxSize;
}

int EmptyQueue(Queue *q)
{
    // 1: q空  0: q不空
    if ((q->rear == q->fron + 1) || (q->rear == (q->fron + 1) % MaxSize))
        return 1;
    else
        return 0;
}

void DelQueue(Queue *q, int *e)
{
    if(EmptyQueue(q))
    {
        printf("EMPTY_ERROR!");
        return;
    }
    q->fron = (q->fron + 1) % MaxSize;
    *e = q->data[q->fron];
}

// 基数排序(分配+收集)
void RadixSort(int arr[], int arrLen)
{
    int t = 1, idx, top = 0;
    Queue que[10];
    for (int i = 0; i < 10; ++i) // 循环队列初始化
        InitQueue(&que[i]);
    for (int i = 0; i < 3; ++i)
    {
        // 分配
        for (int j = 0; j < arrLen; ++j)
        {
            idx = arr[j] / t % 10;
            EnQueue(&que[idx], arr[j]);
        }
        // 收集
        top = 0;
        for (int j = 0; j < 10; ++j)
        {
            while (EmptyQueue(&que[j]) == 0)
                DelQueue(&que[j], &arr[top++]);
        }
        t = t * 10;
    }
}

void main()
{
    int arr[20] = {34, 124, 5, 66, 233, 89, 152, 7, 42, 1};
    int arrLen = 10;
    RadixSort(arr, arrLen);
    printf("\n");
    for (int i = 0; i < arrLen; ++i)
        printf("%d ", arr[i]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值