基数排序

·本篇:328字 大约需要: 1分钟

前言


编程语言:C

数据结构:循环队列


LSD法对1000以内的正整数进行基数排序


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define sf scanf
#define pf printf
#define MAXSIZE 2000

typedef struct
{
int data[MAXSIZE];
int front;
int rear;
} SqQueue;

void InitQueue(SqQueue *Q)
{
Q->front = Q->rear = 0;
}

bool Empty(SqQueue *Q)
{
return Q->rear == Q->front;
}

bool Full(SqQueue *Q)
{
return (Q->rear + 1) % MAXSIZE == Q->front;
}

void EnQueue(SqQueue *Q, int target)
{
if(Full(Q))
pf("队列已满\n");
else
{
Q->data[Q->rear] = target;
Q->rear = (Q->rear + 1) % MAXSIZE;
}
}

void DeQueue(SqQueue *Q, int *target)
{
if(Empty(Q))
pf("队列为空\n");
else
{
*target = Q->data[Q->front];
Q->front = (Q->front + 1) % MAXSIZE;
}
}

bool isEven(int n)
{
return n % 2 == 0;
}

int Pow(int x, int n)
{
if(n == 0)
return 1;
if(isEven(n))
return Pow(x * x, n / 2);
else
return Pow(x, n - 1) * x;
}

void RadixSort(int a[], int rax, int len)
{
int N = 10;
SqQueue *Q = (SqQueue *) malloc(N * sizeof(SqQueue));
for(int i = 0; i < N; i++)
InitQueue(&Q[i]);
for(int i = 0; i < rax; i++)
{
for(int j = 0; j < len; j++)
EnQueue(&Q[a[j] / Pow(10, i) % 10], a[j]);
for(int k = 0, l = 0; k < N; k++)
while(!Empty(&Q[k]))
DeQueue(&Q[k], &a[l++]);
}
for(int i = 0; i < len; i++)
{
if((i + 1) % 30 == 0)
pf("\n");
pf("%d ", a[i]);
}
}