user1016950
user1016950

Reputation: 187

Better minimum and maximum algorithm using an array in Java

I was trying to write a simple max and min method, as I wrote it I just cant help feeling it shouldn’t be this complicated….maybe Im wrong? My maximum code works like this, excuse my poor pseudo code:

Fill an array with 10 random numbers. Create a max variable initialised to 0, because 0 is the lowest max. Compare each element against the max If the element is greater then max, replace the value of max with the element in question

I don’t like the fact I have to initialise max to 0, I feel there might be a better way then this?

My min code works similar except I: Compare my min is lower then the array element. If the element is lower replace min.

What I really don’t like about this is I have to initialise my min to the maximum random number, in this case 50.

My questions are: Is there a better way to do this? Is there a more efficient way to write this code?

import java.util.Random;

public class Main {

public static void main(String[] args) {

    //Declare min and max
    int max=0;
    int min;
    //Array of 10 spaces
    int[] ar=new int[10];
    //fill an array with random numbers between 0 and 50

    for(int i=0;i<10;i++)
    {
        ar[i]=new Random().nextInt(50);
    }

    //Test max algorithm
    //loop trough elements in array
    for(int i=0;i<10;i++)
    {
        //max is set to 0, there should always be a maximum of 0
        //If there isnt 0 will be the maximum

        //If element is greater then max
        //replace max with that element
        if(ar[i]>max)
        {
            max=ar[i];
        }
    }
    System.out.println("The max is "+ max);

    //Test min
    //Initialising min to maximum Random number possible?
    min=50;
    for(int i=0;i<10;i++)
    {
        if(ar[i]<min){
            min=ar[i];
        }
    }
    System.out.println("The min is "+min);


}

}

Upvotes: 2

Views: 13358

Answers (7)

IsolaMonte
IsolaMonte

Reputation: 1

Depending on whether you'd want the max and min-functions in the same method you also have to consider the return type.

So far most suggestions have kept the two separate, meaning it's fine to return an int. However, if you put the max and min-functions into a findLargestDifference-method you'd have to return a long seeing as the largest difference between any given numbers in the int array can be the size of 2 ints. You'd also getting rid of having to loop over the int array twice.

Furthermore I recommend writing unit tests for corner and edge cases instead of printing in a main-method. It helps test your logic early on when implementing it and thus often makes the code cleaner.

See example code below.

public class LargestDifference {

public static long find(int[] numbers) {
    if (numbers == null || numbers.length == 0) {
        throw new IllegalArgumentException("Input cannot be null or empty.");
    }else {
        long currentMax = numbers[0];
        long currentMin = numbers[0];

        for (int i=0; i < numbers.length; i++) {
            if (currentMin > numbers[i]) {
                currentMin = numbers[i];
            }else if (currentMax < numbers[i]) {
                currentMax = numbers[i];
            }
        }
        return currentMax - currentMin;
    }
}

Upvotes: 0

anonymous
anonymous

Reputation: 1

import java.io.*;

public class MultiDimensionalArrayIO {

public static void main(String[] args)throws IOException {
BufferedReader c= new BufferedReader (new InputStreamReader (System.in) );

System.out.print ( "Enter Number Column : " );
int column = Integer.parseInt(c.readLine());
System.out.print ( "Enter Number Row : " );
int row = Integer.parseInt(c.readLine());

int array [][] = new int [column][row];
int max = array [0][0];
int min = array [0][0];
int sum= 0;
for ( int i=0 ; i < array.length; i++){   
for (int j=0 ; j<array[i].length; j++){
    System.out.print("Enter Array Values ["+i+"]["+j+"]: " );
    array[i][j]= Integer.parseInt (c.readLine()); 

        min = Math.min(min , array[i][j]);
        max = Math.max(max , array[i][j]);
        sum += array[i][j];
}    
}

    System.out.println("The Min Number :"+ min);
    System.out.println("The Max Number :"+ max+ " total is "+ sum);

}
}

Upvotes: 0

Pankaj
Pankaj

Reputation: 1

public static void main(String[] args) {
     int[] myArray = {9, 7,9, -40, -10, 40};
    //int[] myArray = {};
    //int[] myArray = {4};
    System.out.println("Difference between max and min = "
            + findDifference(myArray));
}

// Find difference between Max and Min values for a given array
public static int findDifference(int[] arr) {

    if (arr.length == 0) {
        // Log
        System.out.println("Input Array is empty");

        return Integer.MIN_VALUE;
    }

    int min = arr[0];
    int max = arr[0];

    for (int i = 1; i < arr.length; i++) {
        if (arr[i] < min)
            min = arr[i];
        else if (arr[i] > max)
            max = arr[i];
        // Just to check if logic works fine
        System.out.println("Min=" + min + " Max=" + max);
    }

    return max - min;

}

Upvotes: 0

Axel
Axel

Reputation: 14149

Ok, while others were already posting answers, I have taken the time to edit your code into something I think would be more usable.

  1. Make static methods. Those can be reused.
  2. Use an ellipsis (...) because you then can either call the methods on array arguments like in your code, but also with a variable number of arguments as min(5,3,8,4,1).
  3. Initialize with the smallest/biggest possible number the data type provides
  4. To check that your code works, you have to print out the items in the array first, since when you don't know what's in it, there's no way to tell the result is correct.
  5. Base your code on the existing methods in the standard library because these are known to be thoroughly tested and work efficiently (I know, min/max looks like a too trivial example).
  6. I wouldn't bother too much about performance unless you really can show there is a performance problem in your code. Priority should be more like 1st correctness, 2nd readability/maintainability, 3rd performance.

Most of this has been already mentioned by others, but anyway, here's the code:

import java.util.Random;

public class MinMax {

    public static int min(int... args) {
        int m = Integer.MAX_VALUE;
        for (int a : args) {
            m = Math.min(m, a);
        }
        return m;
    }

    public static int max(int... args) {
        int m = Integer.MIN_VALUE;
        for (int a : args) {
            m = Math.max(m, a);
        }
        return m;
    }

    public static void main(String[] args) {

        // fill an array with random numbers between 0 and 50
        int[] ar = new int[10];
        for (int i = 0; i < 10; i++)
        {
            ar[i] = new Random().nextInt(50);
            System.out.println(ar[i]);
        }

        int maxValue = max(ar);
        int minValue = min(ar);

        System.out.println("The max is " + maxValue);
        System.out.println("The min is " + minValue);
    }
}

Upvotes: 5

Alexander
Alexander

Reputation: 23537

You can always grab the first element of the array (i.e. numbers[0]) as the initial value and start the loop from the second element.

int[] numbers = new int[10];
int max, min;
...
min = max = numbers[0];
for(int i = 1; i < numbers.length; ++i) {
    min = Math.min(min, numbers[i]);
    max = Math.max(max, numbers[i]);
}

Upvotes: 6

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340713

Few tips:

  1. Initialize min with first element and start from the second:

    int min = ar[0];
    for(int i=1;i<10;i++)
    
  2. ...or start from:

    int min = Integer.MAX_VALUE;
    

    this approach is better if you expect your array can be empty.

  3. Use Math.min to avoid explicit condition (some may say it's slower though):

    for(int i=0;i<10;i++)
    {
       min = Math.min(min, ar[i]);
    }
    

Upvotes: 2

P.P
P.P

Reputation: 121357

Initialize max to 0 & min to 50 won't work when the numbers change. A more appropriate way is:
1. initialize them to the first element of the array.
2. Use length instead of a constant.

max = ar[0];  
    for(i=0;i<ar.length; i++)  
    {  
            if(ar[i]>max)  
            {  
                max=ar[i];  
            }  
    }

Same for min:

min = ar[0];
for(i=0;i<ar.length; i++)
{
        if(ar[i]<min)
        {
            min=ar[i];
        }
}

Upvotes: 1

Related Questions