下面的代码是我的快速选择(与快速排序非常相似,只是它返回排序数组中的第 n 个项目,而不是整个排序数组)方法。输入是字符串数组(单词),如果给定单词已排序,我必须返回第 n 个索引的单词。
static string QuickSelect(string[] lst, int index) {
if (lst.Length == 1)
{
Console.Write(lst[0]);
return lst[0];
}
else
{
int pivot = _r.Next(lst.Length); // pick a pivot by random number generator
bool[] isDecre = new bool[lst.Length];
string[] WordLeft, WordRight;
int nLeft = 0, nRight = 0;
for (int i = 0; i < lst.Length; i++) // compare values to pivot
{
if (i == pivot) continue;
if (WordCompare(lst[pivot], lst[i]))
{
nRight++;
isDecre[i] = false;
}
else
{
nLeft++;
isDecre[i] = true;
}
}
if (nLeft == index) // pivot was the (index)th item in the list
return lst[pivot];
else
{
WordLeft = new string[nLeft];
WordRight = new string[nRight];
int l = 0, r = 0;
// divide list by saved comparison result
for (int i = 0; i < lst.Length; i++)
{
if (i == pivot) continue;
if (isDecre[i])
{
WordLeft[l] = lst[i];
l++;
}
else
{
WordRight[r] = lst[i];
r++;
}
}
if (nLeft > index)
return QuickSelect(WordLeft, index);
else if (nLeft < index)
return QuickSelect(WordRight, index - nLeft - 1);
}
}
}
问题是这段代码无法运行,抛出“并非所有代码路径都返回值”错误。我认为这与这部分有关:
if (nLeft == index) // pivot was the (index)th item in the list
return lst[pivot];
// build left and right word lists
...
if (nLeft > index)
return QuickSelect(WordLeft, index);
else if (nLeft < index)
return QuickSelect(WordRight, index - nLeft - 1);
如果我在上面的“else if”之后加上一些“else”,错误就会消失。但是当枢轴是第n个索引字符串时,我不想构建左右单词列表。事实上,我认为这种检测到的非价值返回路径有点胡说八道。有什么解决方法吗?