//输出队列中的元素 void print(Queue& que) { Node* p = que.front->next; while (p != NULL) { cout << p->data << " "; p = p->next; } }
//基数排序 void RadixSort(Queue& que) { //定义一个指针数组,数组中存放十个分别指向十个队列的指针 Queue* arr[10]; for (int i = 0; i < 10; i++) { arr[i] = new Queue; } int d = 1; int m = que.lenData(); //取得待排序数据元素中的最大位数
//将初始队列中的元素分配到十个队列中 for(int i = 0; i < m; i++) { Node* p = que.front->next; Node* q; int k; //余数为k,则存储在arr[k]指向的队列中 while (p != NULL) { k = (p->data/d)%10; q = p->next; arr[k]->push(p); p = q; } que.clear(); //清空原始队列
//将十个队列中的数据收集到原始队列中 for (int i = 0; i < 10; i++) { if (!arr[i]->empty()) { Node* p = arr[i]->front->next; Node* q; while (p != NULL) { q = p->next; que.push(p); p = q; } } } for (int i = 0; i < 10; i++)//清空十个队列 { arr[i]->clear(); } d *= 10; } print(que); //输出队列中排好序的元素 } private: Node* front; Node* rear; }; int _tmain(int argc, _TCHAR* argv[]) { Queue oldque; int i; cout << "Please input the integer numbers you want to sort.Input ctrl+z to the end:" << endl; while (cin >> i) { oldque.push(i); } oldque.RadixSort(oldque); cout << endl; return 0; }