1、算法思想
LSD(Least Significant Digit)算法基于字符串的单个字符排序,从最低有效位(即字符串的末尾)开始,直到最高有效位(即字符串的开头),逐步排序。
具体来说,LSD算法首先将所有数字字符串标准化为相同的长度,然后从最低有效位开始,将字符串按照当前位的字符进行排序。排序后,LSD算法继续从低位到高位进行排序,直到所有位都被排序完成。排序过程中,可以使用计数排序或桶排序等简单排序算法。
2、代码实现 C++
首先选择最低位,遍历每个字符串的这一位字符,然后使用计数排序将字符串按照该字符排序。然后,循环地按照字符串中字符从低位到高位的顺序进行排序,直到字符串全部排序完毕。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
// 字符串数组的LSD排序
void lsd_sort(vector<string>& arr)
{
int n = arr.size();
int len = arr[0].size(); // 假设所有字符串具有相同的长度
// 从右向左遍历字符串
for (int i = len - 1; i >= 0; i--)
{
// 创建计数数组以存储字符的频率
vector<int> count(256, 0);
//计算位置i处的字符频率
for (int j = 0; j < n; j++)
{
count[arr[j][i]]++;
}
// 计算计数数组的累积和
for (int j = 1; j < 256; j++)
{
count[j] += count[j - 1];
}
//创建临时数组以存储排序结果
vector<string> temp(n);
// 从右向左遍历原始阵列,并将元素放置在临时数组中
for (int j = n - 1; j >= 0; j--)
{
temp[count[arr[j][i]] - 1] = arr[j];
count[arr[j][i]]--;
}
// 将排序结果从临时数组复制到原始数组
for (int j = 0; j < n; j++)
{
arr[j] = temp[j];
}
}
}
//测验
int main()
{
vector<string> arr = { "cat", "bat", "rat", "hat", "mat" };
lsd_sort(arr);
for (int i = 0; i < arr.size(); i++)
{
cout << arr[i] << " ";
}
return 0;
}