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);
}
}
Arrays.sort(ar)then take the first and last elements.