#include<iostream>
#include<vector>
using namespace std;
typedef struct Node{
int data; //数值
int ge; //位值
int shi;
int bai;
}Node;
void CountSort(vector<Node> A, vector<Node> &B, int k,int n,int bit)
{
int i,j;
vector<int> C(k+1, 0);
if (bit == 0) //先排序个位
{
for (i = 0; i < n; i++)
C[A[i].ge] = C[A[i].ge] + 1;
for (j = 1; j <= k; j++)
C[j] = C[j] + C[j - 1];
for (j = n - 1; j >= 0; j--)
{
B[C[A[j].ge]] = A[j];
C[A[j].ge] = C[A[j].ge] - 1;
}
}
if (bit == 1) //排序十位
{
for (i = 0; i < n; i++)
C[A[i].shi] = C[A[i].shi] + 1;
for (j = 1; j <= k; j++)
C[j] = C[j] + C[j - 1];
for (j = n - 1; j >= 0; j--)
{
B[C[A[j].shi]] = A[j];
C[A[j].shi] = C[A[j].shi] - 1;
}
}
if (bit == 2) //排序百位
{
for (i = 0; i < n; i++)
C[A[i].bai] = C[A[i].bai] + 1;
for (j = 1; j <= k; j++)
C[j] = C[j] + C[j - 1];
for (j = n - 1; j >= 0; j--)
{
B[C[A[j].bai]] = A[j];
C[A[j].bai] = C[A[j].bai] - 1;
}
}
}
void RadixSort(vector<Node> &A, vector<Node> &B, int k, int n,int bit)
{
int i;
for (i = 0; i < bit; i++)
CountSort(A, B, k, n,i);
}
int main(void)
{
vector<Node> A;
int i,ge,shi,bai;
Node temp;
int s[8] = { 329, 457, 657, 839, 436, 720, 355, 999 };
vector<Node> B; //预留空间大一点,防止边界溢出,因为C[A[j]]不会为0 B从1下标开始
for (i = 0; i < 9; i++)
B.push_back({ 0, 0, 0, 0 });
for (i = 0; i < 8; i++) //把数据添加到A中
{
bai = s[i] / 100;
shi = s[i] % 100 / 10;
ge = s[i] % 100 % 10;
temp = { s[i], ge, shi, bai };
A.push_back(temp);
}
RadixSort(A, B, 10, 8, 3);
for (auto i = 1; i < 9;i++)
cout << B[i].data << " ";
cout << endl;
return 0;
}
《算法导论》的基数排序 C++实现
最新推荐文章于 2024-06-27 21:51:33 发布