[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 283

value of max

I am tryaing to Write a method to compute and return the value of max – min where max is the largest element of an int array and min is the smallest element of an int array.  The method is passed the int array and an int value that denotes the number of elements in the array.  You may assume that the int array has at least 1 element in it.

I want some body how know java very well to tell me if it is right or wrong

public int compute(int d[])
{
int size = d.length;
int min=0,max=0;
min=data[0];
max = d[0];
for(int i=0;i<size;i++)
{
if(d[i]<min)
min = d[i];
if(d[i]>max)
max = d[i];
}
return max – min;
}
0
Ansary100
1 Solution

Commented:
The only mistake i see is that you entered min=data[0] and I think you meant min=d[0].  You can also replace
int min=0,max=0;
min=data[0];
max = d[0];
with
int min,max;
min=max=d[0];
But that is just shorthand and does not effect the overall speed of the routine.

Since you have already processed the 0th item, you can also start the for(...) loop with 1:
for(int i=1;i<size;i++)
0

Commented:
Ansary100,

I wonder if you could dispense with initializing min and max to zero, since you re-initialize them right away to d[0].  In other words:

int size = d.length;
int min = d[0];
int max = d[0];
etc.

mathbiol
0

Featured Post

Tackle projects and never again get stuck behind a technical roadblock.