递归逻辑错误Java

时间:2017-05-08 18:41:11

标签: java recursion

我为学校做了这项任务,它希望我使用递归。我是递归的新手,我理解它,但我无法弄清楚为什么这种方法不像它想象的那样工作。这些是给我This is the picture的说明,这是我的代码

// 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时,会弹出一个消息框,并显示“未找到5号”!但是当我将目标值设置为8时,它会在数组中找到它

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

好吧,我已经找到了解决方案。 if-else语句假设在最后返回值。

var str = "{engine{type{condition},age},wheels,model{name},color}"
str = str.replace(/([A-z])\s*{/g, "$1:{")
str = str.replace(/([A-z])\s*([},])/g, "$1:null$2")
console.log(str);