我对学校有这项任务,它希望我使用递归。我是递归的新手,我理解它,但我无法弄清楚为什么这种方法不能按照它的设想工作。这些都给了我,说明,这是我的代码递归逻辑错误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时,它会在数组中找到它
你可以提供一个测试用例,代码不工作吗? –
通过testcase你是指我在哪里运行代码,输出是不正确的? –
是的。提供一个输入样例以及预期输出和计算输出。 –