-1

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?

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
ThePercept
  • 23
  • 1
  • 6

6 Answers6

4

You could return an int[] of min and max. Start with an array of two elements, loop over the array1 like

public static int[] findMinMax(int[] a) {
    int[] result = { Integer.MAX_VALUE, Integer.MIN_VALUE };
    for (int i : a) {
        result[0] = Math.min(result[0], i);
        result[1] = Math.max(result[1], i);
    }
    return result;
}

The result will be an array with the first element being the minimum value2. Then to test it,

public static void main(String[] args) {
    int[] arr = { 3, 20, 1999, 2, 10, 8, 999 };
    int[] minMax = findMinMax(arr);
    System.out.printf("%s: min=%d, max=%d%n", 
            Arrays.toString(arr), minMax[0], minMax[1]);
}

And I get (as I would expect)

[3, 20, 1999, 2, 10, 8, 999]: min=2, max=1999

1Here, with a for-each loop.
2And the second element being the maximum.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • Why findMinMax() is public? Do you want it to call from other classes. Static methods should be called with the class perefix. Why not to use Data Object with two properties instead of array? – Roman C Sep 24 '16 at 20:09
  • @RomanC "Static methods should be called with the class perefix" Not if you statically import it, or it is in the same class' `main` method. – Andy Turner Sep 24 '16 at 20:31
  • @AndyTurner Huh? Static imports are available *only* in Java 7 and higher, other users should use prefix even if it's the same class. – Roman C Sep 25 '16 at 10:30
  • @RomanC [Java 5+](https://en.m.wikipedia.org/wiki/Static_import), actually. – Andy Turner Sep 25 '16 at 17:41
3

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

Fouss
  • 71
  • 5
  • Why would using lists be more efficient? Array accesses are quite fast and there's no need tor dynamic length here. – nanofarad Sep 24 '16 at 19:40
  • Your code is incomplete. What about returning values? How would you return min and max value through the function that returns int? – ElChupacabra Sep 24 '16 at 19:43
  • @hexafraction Because it's one-liners. But yeah, arrays need a few more lines but are faster. – Fouss Sep 24 '16 at 19:44
  • @hexafraction You should clarify what kind of efficiency do you need. If it's a performance issue or something else? – Roman C Sep 24 '16 at 19:50
  • @Fouss Just remove the word "efficient" and word "lists" because you don't know what are you talking. – Roman C Sep 24 '16 at 19:52
  • @Fouss Your code somewhat matches the approach i've used . This helped me . Thanks!! – ThePercept Sep 25 '16 at 03:01
1

Your answer is n^2. To find min and max it only needs to be order n.

In other words you only need to look linear.

Do a loop that looks through the list once. Keep track of min and max as you go. Initially set min = maxvalue and max=minvalue. When you find a value smaller than min, it becomes the new min.

Here is an example in pseudo code.

min = max_int
max = min_int
for (i=0; i < array.length; i++) 
    if array[i] < min 
        min = array[i]
    if array[i] > max
        max = array[i]
netskink
  • 4,033
  • 2
  • 34
  • 46
0

Your approach, if it even works, is needlessly complicated.

  • Create two variables: minNo and maxNo.
  • Set minNo = Integer.MAX_VALUE and maxNo = Integer.MIN_VALUE.
  • Loop through the array. If the element is >= maxNo, assign its value to maxNo. Also (not instead -- i.e., not else if!), if the element is <= minNo, then assign its value to minNo.
  • After the loop, minNo and maxNo will be correctly assigned.
Matthew McPeak
  • 17,705
  • 2
  • 27
  • 59
0

Thanks to the Streaming API in java8, this is a two-liner:

int[] array = new int[] {5,7,2,9,10,24,3,23};

int min = IntStream.of(array).min().getAsInt();
int max = IntStream.of(array).max().getAsInt();

Or as a more efficient 3-liner:

Arrays.parallelSort(array);
int min = array[0];
int max = array[array.length -1];
Mathias Begert
  • 2,354
  • 1
  • 16
  • 26
0
public static void minMax(int []arr){
     int min = arr[0];
     int max = arr[0];
     for(int i=1; i<arr.length; i++){
         min = Math.min(min,arr[i]);
         max = Math.max(max,arr[i]);
     }
//do whatever you want with the max and min
}
omarsafwany
  • 3,695
  • 8
  • 44
  • 75