2017-05-08 145 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是由课程本身预先输入的。我被赋予填补身体的任务 –