java programs

find minimum and maximum values in array java

There are many ways to find out minimum and maximum of an array. Though it is very basic question, I am posting it with possibility of asking this question in interviews to start the discussion.

1. Finding only minimum value of array?

    public class Minimum {
public static void main(String[] args) {
int a[] = {5, -5, 2, 4, -2};
findMinimum(a);
             
}

public static void findMinimum(int[] array) {
int min;
//base condition
if(array == null || array.length == 0) {
System.out.println("Empty array passed.");
} else {
int length = array.length;
min = array[0];
for(int i=1; i<length; i++) {
if(min > array[i]) {
min = array[i];
}
}
System.out.println("Smallest of given array is " + min);
   }
}
}

Sample Output:
Smallest of given array is -5


2. Finding only maximum value of array?

      public class Maximum {
public static void main(String[] args) {
int a[] = {5, -5, 2, 4, -2};
findMax(a);
}

public static void findMax(int[] array) {
int max;
//base condition
if(array == null || array.length == 0) {
System.out.println("Empty array passed.");
} else {
int length = array.length;
max = array[0];
for(int i=1; i<length; i++) {
if(max < array[i]) {
max = array[i];
}
           }
System.out.println("Largest of given array is " + max);
         }
}
  }

Sample Output:

Largest of given array is 5

3. Finding maximum and minimum values of array?

      public class MinimumAndMaximum {
public static void main(String[] args) {
int a[] = {5, -5, 2, 4, -2};
findMinAndMax(a);
}

public static void findMinAndMax(int[] array) {
int min, max;
//base condition
if(array == null || array.length == 0) {
System.out.println("Empty array passed.");
} else {
int length = array.length;
min = array[0];
max = array[0];
for(int i=1; i<length; i++) {
if(max < array[i]) {
max = array[i];
} else if(min > array[i]) {
min = array[i];
}
}
System.out.println("Smallest of given array is " + min);
System.out.println("Largest of given array is " + max);
       }
}
   }

Sample Output:
Smallest of given array is -5
Largest of given array is 5
Powered by Blogger.