# 《算法》笔记 13 - 字符串排序

• 键索引计数法
• 频率统计
• 将频率转换为索引
• 数据分类
• 回写
• 低位优先的字符串排序
• 高位优先的字符串排序

### 键索引计数法

2 Anderson
3 Brown
3 Davis
4 Garcia
1 Harris
3 Jackson
4 Johnson
3 Jones
1 Martin
2 Martinez
2 Miller
1 Moore
2 Robinson
4 Smith
4 Taylor
4 Thomas
2 Thompson
3 White
4 Williams
4 Wilson

#### 将频率转换为索引

for(int r=0;r<R;r++){
count[r+1]+=count[r];
}

### 低位优先的字符串排序

public class LSD {
public static void sort(String[] a, int w) {
int N = a.length;
int R = 256;
String[] aux = new String[N];

for (int d = w - 1; d >= 0; d--) {
int[] count = new int[R + 1];

for (int i = 0; i < N; i++)
count[a[i].charAt(d) + 1]++;

for (int r = 0; r < R; r++)
count[r + 1] += count[r];

for (int i = 0; i < N; i++)
aux[count[a[i].charAt(d)]++] = a[i];

for (int i = 0; i < N; i++)
a[i] = aux[i];

}
}
}

### 高位优先的字符串排序

public class MSD {
private static int R = 256;
private static final int M = 0;
private static String[] aux;

private static int charAt(String s, int d) {
if (d < s.length())
return s.charAt(d);
else
return -1;
}

public static void sort(String[] a) {
int N = a.length;
aux = new String[N];
StdOut.println(String.format("sort(a, %s, %s, %s)", 0, N - 1, 0));
sort(a, 0, N - 1, 0);

}

public static int index;

public static void sort(String[] a, int lo, int hi, int d) {
index++;
if (hi <= lo + M) {
insertion(a, lo, hi, d);
return;
}

int[] count = new int[R + 2];
for (int i = lo; i <= hi; i++)
count[charAt(a[i], d) + 2]++;

for (int r = 0; r < R + 1; r++)
count[r + 1] += count[r];

for (int i = lo; i <= hi; i++)
aux[count[charAt(a[i], d) + 1]++] = a[i];

for (int i = lo; i <= hi; i++)
a[i] = aux[i - lo];

for (int r = 0; r < R; r++) {
sort(a, lo + count[r], lo + count[r + 1] - 1, d + 1);
}
}

// insertion sort a[lo..hi], starting at dth character
private static void insertion(String[] a, int lo, int hi, int d) {
for (int i = lo; i <= hi; i++)
for (int j = i; j > lo && less(a[j], a[j - 1], d); j--)
exch(a, j, j - 1);
}

// exchange a[i] and a[j]
private static void exch(String[] a, int i, int j) {
String temp = a[i];
a[i] = a[j];
a[j] = temp;
}

// is v less than w, starting at character d
private static boolean less(String v, String w, int d) {
// assert v.substring(0, d).equals(w.substring(0, d));
for (int i = d; i < Math.min(v.length(), w.length()); i++) {
if (v.charAt(i) < w.charAt(i))
return true;
if (v.charAt(i) > w.charAt(i))
return false;
}
return v.length() < w.length();
}
}

posted @ 2020-01-01 16:53  zhixin9001  阅读(...)  评论(...编辑  收藏