【发布时间】:2011-10-27 22:32:09
【问题描述】:
下面是来自教科书的 Java 中的 LSD 基数排序实现,用于对字符串数组进行排序,其中每个字符串恰好包含 W 字符。
我想计算运行时数组访问的次数。我读过 LSD 排序应该需要n * c 数组访问,其中n 是字符串数,c 是每个字符串中的字符数。但是,下面的算法会多次访问多个数组。如果我在其中的每一个上增加一个计数器,我最终会得到nc 的重要因子。
那么在算法的上下文中究竟什么构成了“数组访问”?是否只有一个数组访问实例被认为更重要,我应该在这里计算,或者这个示例实际上是一个低效的实现,它使用了比必要更多的数组访问?
public int lsdSort(String[] array, int W) {
int access = 0;
// Sort a[] on leading W characters.
int N = array.length;
String[] aux = new String[N];
for (int d = W-1; d >= 0; d--)
{ // Sort by key-indexed counting on dth char.
int[] count = new int[R+1]; // Compute frequency counts.
for (int i = 0; i < N; i++) {
count[array[i].charAt(d) + 1]++;
}
for (int r = 0; r < R; r++) {
// Transform counts to indices.
count[r+1] += count[r];
}
for (int i = 0; i < N; i++) {
// Distribute.
aux[count[array[i].charAt(d)]++] = array[i];
}
for (int i = 0; i < N; i++) // Copy back.
array[i] = aux[i];
}
return access;
}
【问题讨论】:
-
感谢 Yuval 为提高可读性所做的小修改!
标签: java algorithm radix-sort