//輸出隊(duì)列中的元素 void print(Queue& que) { Node* p = que.front->next; while (p != NULL) { cout << p->data << " "; p = p->next; } }
//基數(shù)排序 void RadixSort(Queue& que) { //定義一個(gè)指針數(shù)組,數(shù)組中存放十個(gè)分別指向十個(gè)隊(duì)列的指針 Queue* arr[10]; for (int i = 0; i < 10; i++) { arr[i] = new Queue; } int d = 1; int m = que.lenData(); //取得待排序數(shù)據(jù)元素中的最大位數(shù)
//將初始隊(duì)列中的元素分配到十個(gè)隊(duì)列中 for(int i = 0; i < m; i++) { Node* p = que.front->next; Node* q; int k; //余數(shù)為k,則存儲(chǔ)在arr[k]指向的隊(duì)列中 while (p != NULL) { k = (p->data/d)%10; q = p->next; arr[k]->push(p); p = q; } que.clear(); //清空原始隊(duì)列
//將十個(gè)隊(duì)列中的數(shù)據(jù)收集到原始隊(duì)列中 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++)//清空十個(gè)隊(duì)列 { arr[i]->clear(); } d *= 10; } print(que); //輸出隊(duì)列中排好序的元素 } 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; }