ThePercept ThePercept - 2 months ago 5
Java Question

How to find the highest and the lowest number stored in an array?

I am trying to print the highest and lowest integer number stored in an array. I am able to print the highest but for the lowest I am not getting the correct result.

Consider my two classes below :

class ArrayUtilityNew
{
public static int findMaxMin(int a[])
{
int n=a.length;
int n2=n-1;
int minNo=0;
int count=0;
int maxNo=0;

for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i]<a[j])count++;

}
//This gives the highest no. if the count is 0
if(count==0)
{
maxNo=a[i];

}

//Lowest no. shall be gained here if the count is greater
// than the no of elements in the array

// if(count>n)
// {
// minNo=a[i];
// }

count=0;
}
return maxNo;
}

}

class ArrayInteractionsNew
{
public static void main(String arr[])
{
int one[]={3,20,1999,2,10,8,999};
int answer=ArrayUtilityNew.findMaxMin(one);
System.out.println("The highest no in the array is "+answer);
}
}


Is the logic behind the second if not correct or is there some other mistake?

How can it be corrected?

Answer

I think your solution is way too complex... A better and more efficient solution would be this:

int n=a.length;
int minNo=a[0];
int maxNo=a[0];

for(int i=1;i<n;i++)
{
     if(a[i] > maxNo) {
         maxNo = a[i];
     } else if(a[i] < minNo) {
         minNo = a[i];
     }
}

// do whatever you want with maxNo and minNo

Also an even more efficient (in the code size way) way would be to use lists or streams because you can do one-liners with it.

EDIT: less ambiguous code and explanations about efficiency

Comments