#include<iostream>
#include<vector>
#include<cmath>
#include<map>
#include<set>
using namespace std;
//手撕一个基数排序
int getNumBitNum(int data)
{
int num = 1;
data /= 10;
while (data!=0)
{
++num;
data /= 10;
}
return num;
}
int getRemainder(int data,int radixNum)
{
int num = data % 10;
--radixNum;
data /= 10;
while (radixNum)
{
num = data % 10;
--radixNum;
data /= 10;
}
return num;
}
void radixSort(vector<int> &allDataVec)
{
//下面找到最大的基数
int maxRadix = 0;
for (const auto &data: allDataVec)
{
int auxNum = getNumBitNum(data);
if (auxNum>maxRadix)
{
maxRadix = auxNum;
}
}
int currNum = allDataVec.size();
//下面进行排序
//下面需要定义一个二维数组用于存储每一个位数
vector<vector<int>> radixVec(19);
for (int i=1;i<=maxRadix;i++)
{
for (auto& item: radixVec)
{
item.resize(currNum +1);
item[0] = 0;
}
//下面进行排序
for (const auto &data: allDataVec)
{
int remainData = getRemainder(data,i);
int index = 9 + remainData;
radixVec[index][0]++;
radixVec[index][radixVec[index][0]]= data;
}
int auxIndex = 0;
//下面进行第一轮排序
for (const auto &item: radixVec)
{
for (int j=1;j<= item[0];j++)
{
allDataVec[auxIndex++] = item[j];
}
}
}
}
void testRadixSort()
{
int num = 0;
cin >> num;
vector<int> allData(num);
cout <<"排序前数据:" << endl;
//用于验证排序是否正确
multiset<int> auxSet;
for (int i=0;i<num;i++)
{
allData[i] = rand();
auxSet.insert(allData[i]);
cout << allData[i] << " ";
}
cout << endl;
radixSort(allData);
cout << "基数排序后数据:" << endl;
auto iter = auxSet.begin();
for (int i = 0; i < num&& iter!= auxSet.end(); i++,iter++)
{
if (allData[i]!= *iter)
{
cout << "基数排序有问题" << endl;
return;
}
cout << allData[i] << " ";
}
cout << endl;
}
int main()
{
//testMergeListNode();
testRadixSort();
return 0;
}
手撕一个基数排序
于 2023-11-14 17:44:28 首次发布