#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]);
}