1. Principle
The so-called radix sort 基数
is 进制
the radix when we talk about it. For example, the base of decimal is 10, and the base of binary is 2. Among them, the nth position from right to left actually represents the n-th power of the base. For example, 101 2 means 1 ⋅ 2 0 + 0 ⋅ 2 1 + 1 ⋅ 2 2 1\cdot2^0+0\cdot2^1+1\cdot2^21⋅20+0⋅21+1⋅22
Then, we can sort by comparing a certain bit first, and then compare another bit for sorting, until all the digits are arranged. For example, we canLSD低位优先法
compare one bit from right to left; or compareMSD高位优先法
one bit from left to right, and compare one bit from left to right.
process:
- Create a base number of queues, and the subscript starts from 0.
- Take the value of a key word and store it in the corresponding numbered queue (a bit like a hash table)
- Starting from 0 or from the base -1 queue, dequeue in increments or decrements, so that the sequence table and linked list formed by dequeues are in a certain order.
- Repeatedly change the number of digits, and 2, 3, until all the digits are in order, and the last out of the queue is in order.
Two. Process
Generally, we use the decimal system, so it is more intuitive to take a base of 10.
Suppose we sort these numbers in a low-order first:
sort the
low-order: sort the
next-low-order: low-order again:
this is the picture.
Three. Code
The code is very very simple, so I don’t want to write it. Copy the code. Novice Tutorial 1.10 Cardinality Sorting :
#include<stdio.h>
#define MAX 20
//#define SHOWPASS
#define BASE 10
void print(int *a, int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d\t", a[i]);
}
}
void radixsort(int *a, int n) {
int i, b[MAX], m = a[0], exp = 1;
for (i = 1; i < n; i++) {
if (a[i] > m) {
m = a[i];
}
}
while (m / exp > 0) {
int bucket[BASE] = {
0 };
for (i = 0; i < n; i++) {
bucket[(a[i] / exp) % BASE]++;
}
for (i = 1; i < BASE; i++) {
bucket[i] += bucket[i - 1];
}
for (i = n - 1; i >= 0; i--) {
b[--bucket[(a[i] / exp) % BASE]] = a[i];
}
for (i = 0; i < n; i++) {
a[i] = b[i];
}
exp *= BASE;
#ifdef SHOWPASS
printf("\nPASS : ");
print(a, n);
#endif
}
}
int main() {
int arr[MAX];
int i, n;
printf("Enter total elements (n <= %d) : ", MAX);
scanf("%d", &n);
n = n < MAX ? n : MAX;
printf("Enter %d Elements : ", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("\nARRAY : ");
print(&arr[0], n);
radixsort(&arr[0], n);
printf("\nSORTED : ");
print(&arr[0], n);
printf("\n");
return 0;
}