Hi, I have a javaproblem that I just can't solve.

"Write a recursive method who returns the largest value in an array with the signature:

``public int max(int[] v)``

(Hint: If you need to, use a private help-method)

It would be easy if it was allowed to change the signature so that it includes a counter, for example like this

``````public int max(int[] v)

int max(int [] v, int len)
{
int m;
if(len == 1)
return v[0];
else if(len == 2)
if(v[0] >= v[1]) {
return v[0];
}
else {
return v[1];
}
else{
m = max(v,len-1);
if (m >= v[len - 1]) {
return m;
}
else {
return v[len - 1];
}
}
}
}``````

But I can't do this. I would be really greatful if anyone cuold help me with this.

4
Contributors
11
Replies
12
Views
7 Years
Discussion Span
Last Post by JamesCherrill

Why can't you do this? An error? If so, please post it!

Btw, if you could post your files on a site, it would be extremely helpful.

Edited by arithehun: n/a

Hmm... Just got it... What you need may be like this...

``````public int max(int[] v) {
return helpFindMax(v, 0, v.length()-1);
}

private int helpFindMax(int[] v, int start, int end) {
// This is the recursive method.
// Do the search here and return the largest integer.
}``````

Edited by Taywin: n/a

Hmm... Just got it... What you need may be like this...

``````public int max(int[] v) {
return helpFindMax(v, 0, v.length()-1);
}

private int helpFindMax(int[] v, int start, int end) {
// This is the recursive method.
// Do the search here and return the largest integer.
}``````

Yep I first thought that this was the way to solve the assignment but then I realised that the max method is no longer recursive. If the help-method is recursive or not has no relevance.

Perhaps I could use the copyOf method?

``````// pseudo code
int max (int [] v) {
if (v has only 1 element) return that element
int[] v1 = copy of v excluding the first element
int maxV1= max(v1)
if (first element of v  >  maxV1) return first element of v;
return maxV1;
}``````
``````// pseudo code
int max (int [] v) {
if (v has only 1 element) return that element
int[] v1 = copy of v excluding the first element
int maxV1= max(v1)
if (first element of v  >  maxV1) return first element of v;
return maxV1;
}``````

Something like this? It gives me a stackOverflow...

``````int max(int [] v) {
if (v.length == 1){
return v[0];
}
int[] v1 = Arrays.copyOfRange(v, 1, (v.length + 1)); //stackOverflow here
int maxV1 = max(v1);
if (v[0] > maxV1){
return v[0];
}
return maxV1;
}``````

Line 5 - you have +1 that shouldn't be there - you are removing the first entry but adding a new zero entry at the end - hence it never stops recursing.

Line 5 - you have +1 that shouldn't be there - you are removing the first entry but adding a new zero entry at the end - hence it never stops recursing.

Aaah.. I misinterpreted the copyOfRange documentation.

Thanks a ton!! You are the man James! :)