I decided to implement a very simple program recursively to see how well Java handles recursion *, and came up a bit. Here is what I wrote:
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 it works great, but since it's a little ugly, I wondered if there is a better way. If anyone has any thoughts / alternatives / syntactic sugar to share, that would be really appreciated!
Ps If you say "use Lisp" you won nothing (but respect). I want to know if this can be done to look good in Java.
* and how much do I handle recursion
java recursion puzzle
Robert Grant
source share