코드 아래에있는 모든 코드 경로가 내 quickselect (sorts 배열이 아닌 정렬 된 배열의 n 번째 항목을 반환한다는 점을 제외하면 quicksort와 매우 비슷합니다) 메소드입니다. 입력은 문자열 (단어)의 배열이며, 주어진 단어가 정렬되면 n 번째 색인의 단어를 반환해야합니다.내 quickselect 메소드
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 번째 인덱스 문자열 일 때 왼쪽 및 오른쪽 단어 목록을 작성하고 싶지 않습니다. 실제로이 비 가치 반환 경로 감지는 다소 난센스라고 생각합니다. 어떤 해결 방법이 있습니까?
'nLeft == index' 값을 반환하지 않으면 간단합니다. –