#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
#define HASH_SIZE 10
void initHashTable(Node** hashTable) {
for (int i = 0; i < HASH_SIZE; i++) {
hashTable[i] = NULL;
}
}
void insertNode(Node** hashTable, int data) {
int hashValue = data % HASH_SIZE;
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (hashTable[hashValue] == NULL) {
hashTable[hashValue] = newNode;
} else {
Node* currentNode = hashTable[hashValue];
while (currentNode->next != NULL) {
currentNode = currentNode->next;
}
currentNode->next = newNode;
}
}
int deleteNode(Node** hashTable, int data) {
int hashValue = data % HASH_SIZE;
Node* currentNode = hashTable[hashValue];
Node* prevNode = NULL;
while (currentNode != NULL) {
if (currentNode->data == data) {
if (prevNode == NULL) {
hashTable[hashValue] = currentNode->next;
} else {
prevNode->next = currentNode->next;
}
int deletedData = currentNode->data;
free(currentNode);
return deletedData;
}
prevNode = currentNode;
currentNode = currentNode->next;
}
return -1;
}
void radixSort(int arr[], int n) {
Node* hashTable[HASH_SIZE];
initHashTable(hashTable);
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
int digit = 1;
while (max / digit > 0) {
for (int i = 0; i < n; i++) {
insertNode(hashTable, arr[i]);
}
int index = 0;
for (int i = 0; i < HASH_SIZE; i++) {
while (hashTable[i] != NULL) {
arr[index++] = deleteNode(hashTable, hashTable[i]->data);
}
}
digit *= 10;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
printf("排序前:");
printArray(arr, n);
radixSort(arr, n);
printf("排序后:");
printArray(arr, n);
return 0;
}