我正在尝试从In-Place Radix Sort工作中获取就地基数排序示例。到目前为止,我有这个:
import std.random;
void swap(ref string i,ref string j) {
string tmp = i;
i = j;
j = tmp;
}
void radixSort(ref string[] seqs, size_t base = 0) {
if(seqs.length == 0)
return;
size_t TPos = seqs.length, APos = 0;
size_t i = 0;
while(i < TPos) {
if(seqs[i][base] == 'A') {
swap(seqs[i], seqs[APos++]);
i++;
}
else if(seqs[i][base] == 'T') {
swap(seqs[i], seqs[--TPos]);
} else i++;
}
i = APos;
size_t CPos = APos;
while(i < TPos) {
if(seqs[i][base] == 'C') {
swap(seqs[i], seqs[CPos++]);
}
i++;
}
if(base < seqs[0].length - 1) {
radixSort(seqs[0..APos], base + 1);
radixSort(seqs[APos..CPos], base + 1);
radixSort(seqs[CPos..TPos], base + 1);
radixSort(seqs[TPos..seqs.length], base + 1);
}
}
void main(string[] args) {
string [] sequences;
for(int n=0;n<10;n++) {
string seq;
for(int i=0;i<10;i++) {
int r = rand()%4;
if(r == 0) seq = seq ~ "A";
if(r == 1) seq = seq ~ "C";
if(r == 2) seq = seq ~ "G";
if(r == 3) seq = seq ~ "T";
}
sequences = sequences ~ seq;
}
writefln("Unsorted");
for(size_t n=0;n<10;n++) {
writefln(sequences[n]);
}
radixSort(sequences,0);
writefln("Sorted");
for(size_t n=0;n<10;n++) {
writefln(sequences[n]);
}
}
然而,这失败了:
radix.d(36): Error: slice expression seqs[0u..APos] is not a modifiable lvalue
radix.d(37): Error: slice expression seqs[APos..CPos] is not a modifiable lvalue
radix.d(38): Error: slice expression seqs[CPos..TPos] is not a modifiable lvalue
radix.d(39): Error: slice expression seqs[TPos..seqs.length] is not a modifiable lvalue
在Digital Mars D Compiler v1.066下。我猜切片是不可变的,但是......我该如何解决这个问题呢?
我是D的新手,并且很感兴趣让这个例子有效。
答案 0 :(得分:7)
如果您想修改引用本身,则只需要ref
。对于数组,这意味着更改长度或重新分配。由于你的基数排序是就地的,我不确定你为什么要这样。