算法系列—低位优先的字符串排序(基于键索引计数法)

原理日后有空补上。今天该回宿舍了- -

此版本可实现相同长度的字符串数组,不同长度稍加改动即可。

C++代码如下:

#include<iostream>
#include <string>
using namespace std;

void LSD(string a[], int size,int W)
{
	//对字符串数组按照前W个字符排序	
	int R = 256;	//基于ascII码
	string *aux = new string[size];

	for (int d = W - 1; d >= 0; d--)
	{
		//根据d个键对字符串排序
		int *count = new int[R + 1];
		
		for (int i = 0; i < R + 1; i++)
		{
			count[i] = 0;
		}
		for (int i = 0; i < size; i++)		//计算出现频率
		{
			count[a[i][d]+1]++;
		}
		for (int i = 0; i < R; i++)		//计算索引
		{
			count[i + 1] += count[i];
		}
		
		for (int i = 0; i < size; i++)		//将元素分类
		{
			aux[(int)count[(int)a[i][d]]++] = a[i];
		}
		for (int i = 0; i < size; i++)		//回写
		{
			a[i] = aux[i];
		}
	}
}

int main()
{
	string a[4] = { "chen","yuee","pang","fei4" };
	LSD(a, sizeof(a) / sizeof(a[0]), sizeof(a) / sizeof(a[0]));
	for (int i = 0; i < 4; i++)
	{
		cout << a[i] << endl;
	}
}


你可能感兴趣的:(算法,字符串排序)