递归函数,无循环 [英] Recursive function without loop
本文介绍了递归函数,无循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个要解决的问题.我有一个整数数组,我想从中获取最小整数.我还得到了应该遵守的功能定义.我不应该在解决方案中使用循环或静态变量.我该如何解决?这是我的功能.
I have a problem want to solve. I have an array of integers from which I want to get the minimum integer. I have also been given a function definition which am supposed to adhere to. I am not supposed to use a loop or a static variable in my solution. How can I solve this? Here is my function.
public static int findMin(int[] numbers, int startIndex, int endIndex){}
请协助.我已经尝试过通过循环执行此实现.
Please assist. I have tried this implementation with a loop.
public static int findMin(int[] numbers, int startIndex, int endIndex) {
int min = 0;
for (int count = startIndex; count <= endIndex; count++) {
if (numbers[count] < min) {
min = numbers[count];
}
}
return min;
}
推荐答案
使用递归时,首先要考虑的是存在状态.这意味着该功能何时存在
First thing you should consider when using recursion is the exist state; which means when the function will be exists
public static int findMin(int[] numbers, int startIndex, int endIndex) {
if(startIndex == endIndex){
return numbers[startIndex];
}
int min = findMin(numbers, startIndex+1, endIndex);
return numbers[startIndex] < min ? numbers[startIndex] : min ;
}
这篇关于递归函数,无循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文