学习目标:
理解和实现基数排序算法
1.基数排序描述
(1)按照元素每位的数值进行排序
(2)定制10个双向队列元素的数组,用于排序时候存取数据
(3)从各位一直往最大位取数,然后放入对应下标的双向队列中再拿出来
2.代码实现
#include<iostream>
#include<queue>
#include<vector>
//中间排序用的
deque<int>qS[10];
//存放每次排序后的结果
queue<int>q;
//初始化,将数组内容放入队列
void init(vector<int>& arr) {
for (auto& it : arr) {
q.push(it);
}
}
//放入基数队列中(这里只举出个位到千位,如果范围更大需要调整)
void put(int i) {
while (!q.empty()) {
int front = q.front();
int tmp;
//个位
if (i == 1) {
tmp = front % 10;
}
//十位
else if (i == 2) {
tmp = front / 10 % 10;
}
//百位
else if(i==3){
tmp = front / 100 % 10;
}
//千位
else {
tmp = front / 1000 % 10;
}
q.pop();
qS[tmp].push_back(front);
}
}
//从基数队列中取出数据
void get() {
for (int i = 0; i < 10; ++i) {
//取回数据
while (!qS[i].empty()) {
q.push(qS[i].front());
qS[i].pop_front();
}
}
}
void run() {
vector<int>arr;//{215,419,121,622,435,231};
for (int i = 0; i < 10; ++i) {
//生成1500-3000的随机数10个
arr.push_back(rand() % 1500 + 1500);
}
cout << "排序前:"; print(arr); cout << endl;
init(arr);
for (int i = 1; i <= 4; ++i) {
put(i);
get();
}
cout << "排序后:";
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
}
输出样例: