How to hashMap an array in Java?

Java recursive array problem. some reason my code is wrong?

  • question is: The maximum-valued element of an integer-valued array can be recursively calculated as follows: If the array has a single element, that is its maximum (note that a zero-sized array has no maximum) Otherwise, compare the first element with the maximum of the rest of the array-- whichever is larger is the maximum value. Write an int method named max that accepts an integer array, and the number of elements in the array and returns the largest value in the array. Assume the array has at least one element. my code is: int max(int[] array, int length){ if(length==0) return array[0]; if(array[length-1]>high) int high = array[length-1]; if(length-1==0) return high; max(array, length-1); } what am i doing wrong? the touring's craft page tells me this --> CTest.java:6: '.class' expected

  • Answer:

    This method does what the hint says: it compares the first element to the last, and then moves that 'last' in by 1 static int recMax(int[] arr, int len) { ...if (len == 1) return arr[0]; ...return Math.max(arr[0], arr[len - 1]); } This has been tested and works just fine!

Ian at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

int max(int[] array, int length){ if(length == 1) return array[0]; else return Math.max(array[length-1], max(array, length -1)); }

Voice of Insanity

well if length==0, it means that there are no elements in the array, so there is no maximum. so maybe you want to throw an exception int max(int [ ] array , int length) { if (length==0) { throw new Exception ("There is no maximum."); } if (length==1) { return arr[length-1]; } //well, the real way to this is instead of the considering the first element, and then the rest, we //consider the last element and then everything up until the last element. Note: the reason we do this is because in C++ for example you can modify the address of the array to be looking at the subarray that starts at location 1 and on. You can't do that in java. } return Math.max(array[length-1] , max(array, length-1) ); // this is how i thought to do it. we want to return the maximum of the last element in the array, or what is biggest in the rest of the array. when length gets to 1, it just returns whatever is there. so it recursively compares the last element of each subarray with the last element of the next subarray.

Ari

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.