低位优先的字符串排序
用于等长字符串中,比如电话号码,IP地址等。
如果字符串的长度为W,那就从右向左以每个位置的字符串作为键,用键索引计数法将字符串排序W遍。
代码实现
#include <stdio.h>
#include <malloc.h>
#include <memory.h>
#include <assert.h>
#define LENGTH 4
#define WORDLENGTH 3
#define CHARLENGTH 256
void LSDSort(char *name[LENGTH]) {
for (int i = 0; i < LENGTH; i=i++) {
puts(name[i]);
}
for (int i = WORDLENGTH-1; i >= 0; i--) {
int count[CHARLENGTH+2];
memset(count, 0, sizeof(int)*CHARLENGTH);
//计算频率
for (int j = 0; j < LENGTH; j++) {
count[name[j][i]+1]++;
printf("%d, %d. %c\n",j, i, name[j][i]);
}
//索引
for (int j = 0; j < CHARLENGTH + 2 && j + 1<CHARLENGTH + 2; j++) {
count[j + 1] += count[j];
}
//分类
char *tmp[LENGTH];
for (int j = 0; j < LENGTH; j++) {
tmp[count[name[j][i]]++] = name[j];
}
//回写
for (int j = 0; j < LENGTH; j++) {
name[j] = tmp[j];
}
}
}
void main() {
char *name[LENGTH] = {
"abc",
"def",
"ape",
"apk",
};
LSDSort(name);
}