MSD最高有效位优先排序
作者:
Ronin_56
,
2024-11-01 19:06:00
,
所有人可见
,
阅读 2
// MSD最高位优先排序
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int N = 1e6 + 5;
int n;
int g[N];
//digit表示最大数的位数,left和right分别指向该最高位为数字i时在数组中的区间
void MSD_sort(int g[], int left, int right, int digit)
{
if (left >= right || digit <= 0) return ;
int count[10] = {0};
int temp[right - left + 1] = {0};
int div = pow(10, digit - 1);
for (int i = left; i <= right; ++ i)
{
int num = (g[i] / div) % 10;
count[num] ++ ;
}
int startIndex[10] = {0};
int prevCount = 0;
for (int i = 0; i < 10; ++ i)
{
startIndex[i] += prevCount;
prevCount += count[i];
}
for (int i = left; i <= right; ++ i)
{
int num = (g[i] / div) % 10;
temp[startIndex[num]] = g[i];
startIndex[num] ++ ;
}
for (int i = left; i <= right; ++ i)
{
g[i] = temp[i];
}
for (int i = 0; i < 10; ++ i)
{
int backetLeft = left + startIndex[i] - count[i];
int backetRight = left + startIndex[i] - 1;
MSD_sort(g, backetLeft, backetRight, digit - 1);
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; ++ i)
{
cin >> g[i];
}
int digit = 0;
for (int i = 0; i < n; ++ i)
{
int len = 0;
int x = g[i];
while (x)
{
x /= 10;
len ++ ;
}
digit = max(digit, len);
}
MSD_sort(g, 0, n - 1, digit);
for (int i = 0; i < n; ++ i)
{
cout << g[i] << ' ';
}
return 0;
}