输入格式:
输入第一行给出正整数N(≤105),随后一行给出N个(长整型范围内的)整数,其间以空格分隔。
输出格式:
在一行中输出从小到大排序后的结果,数字间以1个空格分隔,行末不得有多余空格。
输入样例:
11
4 981 10 -17 0 -20 29 50 8 43 -5
输出样例:
-20 -17 -5 0 4 8 10 29 43 50 981
/* 链式基数排序 ❥(ゝω・✿ฺ) ❥(ゝω・✿ฺ) */ /* 这题的关键是将负数的处理 将余数为-9 ~ -1 转化为 0 - 8 而余数为 0 - 9转化为 9 - 18 */ #include <bits/stdc++.h> #define MIN 0xFFFFFFFD using namespace std; typedef struct Node { int data; struct Node *Next; }Node, *NodePtr; typedef struct SLList { Node *head, *tail; }SLList; int GetKeySize(int n) { int cnt = 0; while(n != 0) { n /= 10; ++cnt; } return cnt; } int Ord(int val, int i) { int divisor = 1; for(int n = 1; n < i; ++n) divisor *= 10; if(abs(val) / divisor < 10) return (val / divisor) % 10; else return (abs(val) / divisor) % 10; } void Distribute(SLList &L, SLList *temp, int n) { NodePtr node = L.head; NodePtr tmpPtr; int pos; while(node != NULL) { tmpPtr = node->Next; node->Next = NULL; pos = Ord(node->data, n) + 9; if(temp[pos].head == NULL) { temp[pos].head = temp[pos].tail = node; } else { temp[pos].tail->Next = node; temp[pos].tail = node; } node = tmpPtr; } L.head = L.tail = NULL;//这里要置空 } void Collect(SLList &L, SLList *temp) { for(int i = 0; i < 19; ++i) { if(temp[i].head != NULL) { if(L.head == NULL) { L.head = temp[i].head; L.tail = temp[i].tail; } else { L.tail->Next = temp[i].head; L.tail = temp[i].tail; } } temp[i].head = temp[i].tail = NULL;//这里要置空 } } void RadixSort(SLList &L, int KeySize) { SLList temp[25]; for(int i = 0; i < 25; ++i) { temp[i].head = temp[i].tail = NULL; } for(int i = 1; i <= KeySize; ++i) { Distribute(L, temp, i); Collect(L, temp); NodePtr cur = L.head; } } int main() { int N, val, pos, KeySize, MAX = MIN; SLList L; L.head = L.tail = NULL; scanf("%d", &N); for(int i = 1; i <= N; ++i) { NodePtr node = (NodePtr)malloc(sizeof(Node)); scanf("%d", &val); node->data = val; node->Next = NULL; if(i == 1) { L.tail = L.head = node; } else { L.tail->Next = node; L.tail = L.tail->Next; } if(abs(val) > MAX) MAX = abs(val); } KeySize = GetKeySize(MAX); RadixSort(L, KeySize); NodePtr cur = L.head; printf("%d", cur->data); cur = cur->Next; while(cur != NULL) { printf(" %d", cur->data); cur = cur->Next; } }