键索引排序法是字符串排序算法的一种,是低位优先字符串排序(LSD)与高位优先字符串排序(MSD)的基础。
在此,用C++写出这个算法的一个例子。
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
vector<pair<string, int>> index_string = { {"Gary", 2}, {"Jenny", 3}, {"Tom", 2}, {"Jane", 1}, {"Wade", 1}, {"Tank", 3}};
cout << "Before sorting:\n";
for (auto& i : index_string) {
cout << i.first << ", " << i.second << "\n";
}
//1.元素频次统计,这一步是要统计出每个组有多少个成员,方便后面按组号重排列
//注意:count[0]一定是0;count[index + 1]++;意思是:以组号1为例,组号1的索引应该是组号0的最后一个元素的下一个位置;因此,每来一个组号0的元素,组号1的起始索引都要向后腾一个位置
int count[5] = {0};
for (auto& i : index_string) {
count[i.second + 1]++;
}
//2.用上一步统计的元素频次生成一个组号索引;排序时,某个组的元素将会放在对应索引处
for (int i = 1; i < 5; i++) {
count[i] += count[i - 1];
}
//3.重排序,对原数组的元素进行重排
vector<pair<string, int>> aux;
aux.resize(index_string.size());
for (auto& i : index_string) {
aux[count[i.second]++] = i;
}
//4.回写
index_string = aux;
cout << "Result :\n";
for (auto& i : index_string) {
cout << i.first << ", " << i.second << "\n";
}
}