2012-12-23 2 views
0

코드 아래에있는 모든 코드 경로가 내 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 번째 인덱스 문자열 일 때 왼쪽 및 오른쪽 단어 목록을 작성하고 싶지 않습니다. 실제로이 비 가치 반환 경로 감지는 다소 난센스라고 생각합니다. 어떤 해결 방법이 있습니까?

+0

'nLeft == index' 값을 반환하지 않으면 간단합니다. –

답변

2

아니요, 대안이 없습니다.

또는을 반환해야 메서드의 모든 경로에서 예외가 throw됩니다 (해당 메서드에서는 처리되지 않음).

편집 : 한편

, 당신의 조건 :

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 (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); 
return QuickSelect(WordRight, index - nLeft - 1); 
+1

if의 내용을 else로 드롭 할 수도 있습니다. –

+0

맞아, 너무 떨어질 수있어. 답변을 업데이트했습니다. – MarcinJuraszek

+0

완벽하게 해결되었습니다. btw 나는 "else"키워드를 선호한다. 가독성을 약간 향상시키지 않겠는가? 또는 속도 위반이 있습니까? – thkang

0


if (nLeft > index)
return QuickSelect(WordLeft, index);
else if (nLeft < index)
return QuickSelect(WordRight, index - nLeft - 1);
else //nLeft== index
return "something";

두 조건이 모두 실패하면 여전히 값을 반환해야하므로 반환 값을 기반으로 해당 사례를 처리 할 수 ​​있습니다.

0

코드는 지정된 조건이 참일 경우에만 값을 반환합니다. 세 가지 조건을 지정 했으므로이 조건 중 하나가 참일 때 메서드는 값을 반환하지만이 경우 세 가지 조건이 모두 거짓 일 경우 응용 프로그램에서 수행 할 작업을 알 수 없으므로 오류가 발생합니다. 이 당신이 이러한 조건이 거짓이 될 때 수행됩니다 것을 지정하지 않았기 때문에 값이 돌아 오지, 그리고 당신이 오류가 발생하는 이유 부울이 true 또는 false

if (nLeft == index) //Continue if the condition becomes true 
    return lst[pivot]; //Return a value 
... 
if (nLeft > index) //Continue if the condition becomes true 
    return QuickSelect(WordLeft, index); //Return a value 
else if (nLeft < index) //Continue if the condition becomes true 
    return QuickSelect(WordRight, index - nLeft - 1); //Return a value 

당신은 추가해야 할 수 그건 것 단순히 이들 조건 (a bool위한 다른 가능성)가 잘못된 경우

if (nLeft == index) //Continue if the condition becomes true 
    return lst[pivot]; //Return a value 
... 
if (nLeft > index) //Continue if the condition becomes true 
    return QuickSelect(WordLeft, index); //Return a value 
else if (nLeft < index) //Continue if the condition becomes true 
    return QuickSelect(WordRight, index - nLeft - 1); //Return a value 
else //Continue if these conditions become false 
    return /* value */; //Return a value 
,174

예를 다른 값을 반환하는 애플리케이션을 말한다이 방법 행

감사합니다,
당신이 도움이되기를 바랍니다. :)

관련 문제