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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
| #include <stdio.h> #include <stdlib.h>
typedef struct Node { int data; struct Node* next; } Node;
typedef struct Queue { Node* front; Node* rear; } Queue;
Queue queue[10]; int divisior = 1;
void initQueue(Queue* que) { Node* p = malloc(sizeof(Node)); if (p != NULL) { p->data = 0; p->next = NULL; (*que).front = p; (*que).rear = p; } else { printf("node apply error!\n"); } }
void push(Queue* que, int e) { Node* p = malloc(sizeof(Node)); if (p != NULL) { p->data = e; p->next = NULL; (*que).rear->next = p; (*que).rear = p; } else { printf("node apply error!\n"); } }
void clear(Queue* que) { (*que).front->next = NULL; (*que).rear = (*que).front; }
int maxBit(Queue* que) { Node* p = (*que).front->next; int maxData = p->data; while (p != NULL) { if (maxData < p->data) { maxData = p->data; } p = p->next; } int b = 0; while (maxData > 0) { maxData /= 10; b++; } return b; }
int getKey(Node* q) { int k = 0; k = ((*q).data / divisior) % 10; return k; }
void distributeRadix(Queue* que) { for (int i = 0; i < 10; i++) { initQueue(&queue[i]); } Node* p = (*que).front->next; while (p != NULL) { int k = getKey(p); queue[k].rear->next = p; queue[k].rear = p; p = p->next; queue[k].rear->next = NULL; } clear(que); }
void collectRadix(Queue* que) { int index = 0; for (index = 0; index < 10; index++) { if (&queue[index].front->next->data != NULL) { break; } } Node* p = queue[index].front->next; while (p != NULL) { (*que).rear->next = p; (*que).rear = p; p = p->next; (*que).rear->next = NULL; } for (index++; index < 10; index++) { Node* q = queue[index].front->next; while (q != NULL) { (*que).rear->next = q; (*que).rear = q; q = q->next; (*que).rear->next = NULL; } } for (int i = 0; i < 10; i++) { clear(&queue[i]); } divisior *= 10; }
void radix(Queue* que) { int b = maxBit(que); for (int i = 0; i < b; i++) { distributeRadix(que); collectRadix(que); } }
void print(Queue* que) { Node* p = (*que).front->next; while (p != NULL) { printf("%d ", p->data); p = p->next; } printf("\n"); }
int main() { Queue que; initQueue(&que); int arr[] = { 1234, 5678, 9101, 2345, 6789, 1011, 1213, 1415, 1617, 1819, 2021, 2223, 2425, 2627, 2829,3032, 3233, 3435, 3637, 3839 }; int len = sizeof(arr) / sizeof(int); for (int i = 0; i < len; i++) { push(&que, arr[i]); } printf("排序前序列:\n"); print(&que); radix(&que); printf("排序后序列:\n"); print(&que); return 0; }
|