基数排序与后缀数组

Key-Indexed Counting

典型的思路比代码好懂的算法。Key-indexed Counting 算法的目的是:Sort an array a[] of N integers between 00 and R−1R-1. 我们照着代码对一个样例进行分析:

java
int N = a.length;
int[] count = new int[R+1];

for (int i = 0; i < N; ++i)	count[a[i]+1]++;
for (int r = 0; r < R; ++r)	count[r+1] += count[r];
for (int i = 0; i < N; ++i)	aux[count[a[i]]++] = a[i];
for (int i = 0; i < N; ++i)	a[i] = aux[i];

第一步:Count frequencies of each letter using key as index.

计算 count[] 桶数组

第二步:Compute frequency cumulates which specify destinations.

对 count[] 数组计算前缀和,从而得到每种 key 排序后的起始位置

在第二次循环后,count[i] 的意义是严格小于 (这是由第一次循环中计算 count[] 时 offset by 1 保证的) key i 的 keys 的个数,也即 key i 在排序后数组中的初始位置。

第三步:Access cumulates using key as index to move items.

注意 ++: count[i] 始终记录 key i 将会在的位置

每次将 key i 根据 count[i] 移动到指定的位置后,count[i]++;这是因为当我们要为下一个 key i 的出现做好“准备”。由于我们是按照 keys 的原顺序扫描的,key-indexed counting 是一个 stable 的排序算法。

第四步:Copy aux[] back into original array.

Key-indexed array counting uses ∼11N+4R\sim11N+4R array assesses to sort NN items whose keys are integers between 00 and R−1R-1.

在之前学习排序算法时,我们提到过 compare-based sorting algorithm 的下界是 ∼Nlog⁡N\sim N\log{N} 次比较。

注意这与 key-indexed counting 算法的线性复杂度并不冲突。key-indexed counting 实际上是桶排序的变种,它并不是 compare-based 的排序算法!

Radix Sort

基数排序的原理是将整数按位数切割成不同的数字,按位进行排序。因此其也完美符合字符串排序的要求:字符串是由一系列字符组成的,每一个字符就相当于其的一个“位数”。

LSD Radix Sort

LSD Radix Sort 即 Least-Significant-Digit-First Radix Sort;它从键值的低位到高位逐位进行排序。

java
public class LSD {
    public static void sort(String[] a, int W) {    // fixed-length W strings
        int R = 256;    // radix R
        int N = a.length;
        String[] aux = new String[N];
        for (int d = W-1; d >= 0; --d) {    // do key-indexed counting from LSD to MSD
            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];
        }
    }
}

这个做法确实非常的优雅,正确性也比较符合直觉;由于采用了 key-indexed counting,每一轮排序都能保证是 stable 的;因此 LSD Radix Sort 是一个 stable 的排序算法。

Pf. [By induction on i] After pass ii, strings are sorted by last ii characters.

  • If two strings differ on sort key, key-indexed sort puts them in proper relative order.
  • If two strings agree on sort key, stability keeps them in proper relative order.

注意,以上的代码是针对 fixed-length strings 的。对于 variable-length strings,我们只需要用 -1 补齐每个字符串即可。(在 C 语言中则没有这种顾虑,因为每个字符串的末尾都添加了 '\0' 标识符)

MSD Radix Sort

类似的,MSD Radix Sort 即 Most-Significant-Digit-First Radix Sort,从键值的高位到低位逐位进行排序。很容易发现在 MSD 中我们需要引入 partition,按照类似 quick sort 的结构进行排序。

  • Partition array into RR pieces according to first character (use key-indexed counting).
  • Recursively sort all strings that start with each character. (do key-indexed counting in each subarray)

与 LSD 相比,MSD 的劣势在于:

  • 更多的空间。特别是每一层递归都需要为 count[] 数组分配空间。
  • 递归带来的较低效率。可以采用 cutoff to insertion sort for small subarrays 优化。
  • Inner loop has a lot of instructions.
  • Cache inefficient: accesses memory "randomly".

MSD examines just enough characters to sort the keys.

以上的种种缺点与相对比较复杂的代码换来的是 MSD 理论复杂度上的优势。由于 number of characters examined only depends on keys, MSD can be sublinear in input size!

java
private static int charAt(String s, int d) {    // for variable-length strings
	if (d < s.length())	return s.charAt(d);
    return -1;
}

public static void sort(String[] a) {
    aux = new String[a.length];    // can recycle aux[] array but not count[] array
    sort(a, aux, 0, a.length-1, 0);
}

private static void sort(String[] a, String[] aux, int lo, int hi, int d) {
    if (hi <= lo)	return;
    int[] count = new int[R+2];
    for (int i = lo; i <= hi; ++i)
        count[charAt(a[i], d) + 2]++;   // the existence of -1
    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 R subarrays recursively
        sort(a, aux, lo + count[r], lo + count[r+1] - 1, d+1);
}

3-way Radix Quicksort

MSD 实际上使用的是 R-way Partitioning:它使用 key-indexed counting 将原数组分为 R 个 subarrays,每个 subarray 中的字符串都具有相同的第一关键字,接下来再递归的对这 R 个 subarrays 进行排序。

而 3-way radix quicksort 则借助了 3-way quicksort 的思想对 MSD 进行改造。对于所有第一关键字,选择一个 partitioning item,并对应的将所有字符串分为 less, equal 与 greater 三个 subarrays。

Does not re-examine characters equal to the partitioning char

与朴素的 Quicksort for strings 相比,3-way radix quicksort 能够做到:

  • Use ∼2Nln⁡N\sim 2N\ln{N} character compares (instead of string compares) on average for random strings.
  • Avoids re-comparing long common prefixes.

与 MSD (R-way radix sort) 相比 3-way radix quicksort 有以下优势:

  • Has a short inner loop.
  • Is cache-friendly.
  • Is in-place.

注意 3-way radix quicksort 并未使用 key-indexed counting;但它仍然是一种 radix sort,因为它是按位进行排序的。从这个意义上来讲,比起 MSD,3-way radix quicksort 的亲缘关系更偏向于传统的 quicksort。

java
private static void sort(String[] a) {
    sort(a, 0, a.length - 1, 0);
}

private static void sort(String[] a, int lo, int hi, int d) {
    if (hi <= lo)	return;
    int lt = lo, gt = hi;
    int v = charAt(a[lo], d);
    int i = lo + 1;
    while (i <= gt) {
        int t = charAt(a[i], d);
        if      (t < v) exch(a, lt++, i++);
        else if (t > v) exch(a, i, gt--);
        else            i++;
    }
    
    sort(a, lo, lt-1, d);
    if (v >= 0) sort(a, lt, gt, d+1);
    sort(a, gt+1, hi, d);
}

Performance Analysis

对 NN 个 WW 位的字符串进行排序,若字符集大小为 RR,我们有:

algorithm guarantee random stable? operation
quicksort 1.39Nlg⁡N1.39N\lg{N} 1.39Nlg⁡N1.39N\lg{N} no compareTo()
LSD 2WN2WN 2WN2WN yes charAt()
MSD 2WN2WN Nlog⁡RNN\log_{R} N yes charAt()
3-way radix quicksort 1.39WNlg⁡R1.39WN\lg{R} 1.39Nlg⁡N1.39N\lg{N} no charAt()

注意 compareTo() 操作的复杂度与字符串间的最长公共前缀的长度有关,因此其最坏是 Ω(W)\Omega(W) 的;而 charAt() 是 constant time 的操作。

对于 string sorting algorithms,我们能够作出以下总结:

  • We can develop linear-time sorts (LSD): key compares not necessary for string keys; we use characters as index in an array.
  • We can develop sublinear-time sorts (MSD): input size is amount of data in keys (not number of keys) and not all of the data has to be examined.
  • 3-way radix quicksort is asymptotically optimal.
  • Long strings are rarely random in practice: we may need specialized algorithms.

Suffix Arrays

接下来我们介绍后缀数组:一个字符串处理的终极利器,也是进一步理解后缀系算法 (后缀树,后缀自动机) 的基础。对于一个字符串,我们用数组保存其所有的后缀并进行排序,得到的数组即为后缀数组。

Bottleneck Problem. Suffix sort an arbitrary string of length NN.

后缀排序问题本质上是字符串排序问题,所以以上介绍的 LSD,MSD 与 3-way radix quicksort 甚至传统的 quicksort 均可以作为后缀排序采用的算法;但其效率 ( Ω(WN)\Omega(WN) 或 Ω(N2lg⁡N)\Omega(N^2\lg{N}) ) 难以满足实际应用的要求。

利用后缀这一特殊的性质,我们能设计出性能更加优越的后缀排序算法:Manber-Myers 倍增算法能够做到最坏 Nlg⁡NN\lg{N} 的时间复杂度,DC3 算法与后缀树能够做到线性的时间复杂度。

Manber-Myers MSD algorithm overview.

  • Phase 00: sort on first character using key-indexed counting sort.
  • Phase ii: given array of suffixes sorted on first 2i−12^{i-1} characters, create array of suffixes sorted on first 2i2^i characters.

后缀数组的经典应用之一:Keyword-in-context search (本博客的搜索功能就是一种文本关键字搜索)。

  • Proprocess: suffix sort the text.
  • Query: binary search for query; scan until mismatch.

后缀数组的经典应用之二:Longest repeated substring。

  • Brute-force: Try all indices ii and jj for start of possible match, and compute longest common prefix (LCP) for each pair. 该做法的复杂度为 Ω(DN2)\Omega (DN^2),其中 DD 是 LCP 的长度。
  • 后缀数组做法:在求出后缀数组后对每个相邻的后缀求 LCP 即可。
java
public String lrs(String s) {
    int N = s.length;
    String[] suffixes = new String[N];
    for (int i = 0; i < N; ++i)
        suffix[i] = s.substring(i, N);   // String class: linear time & space
    Arrays.sort(suffixes);               // sort suffixes
    String lrs = "";
    for (int i = 0; i < N-1; ++i) {
        int len = lcp(suffixes[i], suffixes[i+1]);
        if (len > lrs.length())
            lrs = suffixes[i].substring(0, len);
    }
    return lrs;
}
CC BY-NC-SA 4.0
正在加载评论…