2017-05-08 139 views
-2

我對學校有這項任務,它希望我使用遞歸。我是遞歸的新手,我理解它,但我無法弄清楚爲什麼這種方法不能按照它的設想工作。這些都給了我,說明This is the picture,這是我的代碼遞歸邏輯錯誤Java

// This method will be completed by the student! 
    // The student should implement the binary search algorithm using recursion. The 
    // method will originally be called by the GUI logic when the Search button is clicked. 
    public int binarySearch(Integer[] targetArray, int targetValue, int lowIndex, int highIndex){ 
     if (lowIndex > highIndex) 
      return -1; 
     int midIndex = lowIndex + (highIndex - lowIndex)/2; 
     if (targetValue == targetArray[midIndex]) 
      return midIndex; 
     if(targetArray[midIndex] > targetValue) 
      binarySearch(targetArray, targetValue, lowIndex, midIndex - 1); 
     else if(targetArray[midIndex] < targetValue) 
      binarySearch(targetArray, targetValue, midIndex + 1, highIndex); 
     return -1; // replace this with your recursive binary search code 
     } 

程序會要求用戶在目標值進入。然後它將使用遞歸搜索數組來判斷目標值是否在數組中。該數組包含數字{1,3,5,6,8,9,10,12,14,15}。當我搜索數字5時會彈出一個消息框,並顯示「Number 5 not found!」但是當我將目標值設置爲8時,它會在數組中找到它

+2

你可以提供一個測試用例,代碼不工作嗎? –

+0

通過testcase你是指我在哪裏運行代碼,輸出是不正確的? –

+0

是的。提供一個輸入樣例以及預期輸出和計算輸出。 –

回答

0

那麼我已經想出瞭解決方案。 if-else語句假設在最後返回值。

public int binarySearch(Integer[] targetArray, int targetValue, int lowIndex, int highIndex){ 
    if (lowIndex > highIndex) 
     return -1; 
    int midIndex = lowIndex + (highIndex - lowIndex)/2; 
    if (targetValue == targetArray[midIndex]) 
     return midIndex; 
    if(targetArray[midIndex] > targetValue) 
     return binarySearch(targetArray, targetValue, lowIndex, midIndex - 1); 
    else //if(targetArray[midIndex] < targetValue) 
     return binarySearch(targetArray, targetValue, midIndex + 1, highIndex); 
    //return -1; // replace this with your recursive binary search code 
    } 
+0

正確。以-1的硬返回結束遞歸語句意味着無論你使用何種路徑,每次調用都會碰到最後的'else if'即使找到結果也會返回-1。 – leigero

1

我認爲評論源自評論?

public int binarySearch(int[] targetArray, int targetValue, 
     int lowIndex, int highIndex) { 
    if (lowIndex > highIndex) 
     return -1; 
    int midIndex = lowIndex + (highIndex - lowIndex)/2; 
    if (targetValue == targetArray[midIndex]) 
     return midIndex; 
    if (targetArray[midIndex] > targetValue) 
     return binarySearch(targetArray, targetValue, lowIndex, midIndex - 1); 
    else //if(targetArray[midIndex] < targetValue) 
     return binarySearch(targetArray, targetValue, midIndex + 1, highIndex); 
    } 

解決方法是刪除最後一個else-if。

你也沒有返回遞歸找到的索引的結果。

(一種int[]參數,而不是Integer[]會更好。)

而且通常(的99%)程序員使用{}if

+0

我已經評論過最後一部分否則,如果我在最後註釋了返回-1,但由於它在末尾沒有返回類型,則會引發錯誤。所以我把返回-1返回,它仍然有相同的結果 –

+0

因爲你不返回遞歸返回值,對於遞歸結果-1(最後一個返回)被返回。 –

+0

方法,方法參數和返回-1是由課程本身預先輸入的。我被賦予填補身體的任務 –