below code is my quickselect (something very similar to quicksort except that it returns nth item in the sorted array, not the whole sorted array) method. the input is array of strings(words), and I have to return the word of nth index if the given words are sorted.
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);
}
}
}
the problem is that this code won’t run, throwing “not all code paths return a value” error. I think it has to do with this part:
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);
if I put some ‘else’ after above ‘else if’, the error goes away. But I don’t want to build left and right word lists when the pivot was the nth index string. In fact I think this non-value-returning-path-detected is kinda nonsense. is there any workaround?
No, there is no workaround.
You have to return value or throw an exception (which won’t be handled in that method) in all paths in the method.
EDIT:
On the other hand, your conditions:
could be changed to this: