通过递归找到数组中最大的正整数 [英] Finding the largest positive int in an array by recursion
本文介绍了通过递归找到数组中最大的正整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我决定递归地实现一个非常简单的程序,看看 Java 处理递归的效果如何*,结果有点简短.这就是我最终写的:
I decided to implement a very simple program recursively, to see how well Java handles recursion*, and came up a bit short. This is what I ended up writing:
public class largestInIntArray {
public static void main(String[] args)
{
// These three lines just set up an array of ints:
int[] ints = new int[100];
java.util.Random r = new java.util.Random();
for(int i = 0; i < 100; i++) ints[i] = r.nextInt();
System.out.print("Normal:"+normal(ints,-1)+" Recursive:"+recursive(ints,-1));
}
private static int normal(int[] input, int largest) {
for(int i : input)
if(i > largest) largest = i;
return largest;
}
private static int recursive(int[] ints, int largest) {
if(ints.length == 1)
return ints[0] > largest ? ints[0] : largest;
int[] newints = new int[ints.length - 1];
System.arraycopy(ints, 1, newints, 0, ints.length - 1);
return recursive(newints, ints[0] > largest ? ints[0] : largest);
}
}
这很好用,但由于它有点难看,我想知道是否有更好的方法.如果有人有任何想法/替代方案/语法糖可以分享,那将不胜感激!
And that works fine, but as it's a bit ugly I wondered if there was a better way. If anyone has any thoughts/alternatives/syntactic sugar to share, that'd be much appreciated!
附言如果你说使用 Lisp",你什么也得不到(但尊重).我想知道这是否可以在 Java 中看起来不错.
P.s. If you say "use Lisp" you win nothing (but respect). I want to know if this can be made to look nice in Java.
*以及我如何处理递归
推荐答案
2 项改进:
- 没有数组的副本(仅使用偏移量)
无需给出当前最大值
- no copy of the array (just using the offset)
no need to give the current max
private static int recursive(int[] ints, int offset) {
if (ints.length - 1 == offset) {
return ints[offset];
} else {
return Math.max(ints[offset], recursive(ints, offset + 1));
}
}
以 recursive(ints, 0)
开始递归.
这篇关于通过递归找到数组中最大的正整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文