Arrays: Program to search minimum & maximum element



Given an array arr[] of size n, find the maximum and minimum element present in the array.
For this purpose, we will use two variables max and min and then compare them with each element and
replace them with the appropriate element so as to get the maximum and minimum element from the array.

 
Approach
  1. We will use two integer variables "max" and "min". Initialize them with the first element of the input array(array[0])
  2. Using a for loop, traverse array
  3. If the current element is more than max, then update max with current element
  4. For a minimum element if the current element is less than min, then update min with current element
  5. At the end of the for loop, "max" and "min" will contain the maximum and minimum elements of the array
 
Java Code
                
    public class MinAndMax {

        public int getMaxValue(int [] arr) {
           int max = arr[0];
      
           for(int i = 0; i < arr.length; i++ ) {
                  if(arr[i] > max) {
                     max = arr[i];
                  }
           }
              return max;
        }

        public int getMinValue(int [] arr) {
              int min = arr[0];
      
           for(int i = 0; i < arr.length ; i++ ) {
                  if(arr[i] < min) {
                     min = arr[i];
                  }
           }
           return min;
        }

        public static void main(String args[]) {

           int[] myArray = {20, 80, 60, 40, 100};
           MinAndMax m = new MinAndMax();

           System.out.println("Maximum value in the array    is::"+m.getMaxValue(myArray));
           System.out.println("Minimum value in the array is::"+m.getMinValue(myArray));

        }
 }
              

Output:

Maximum value in the array is :100
Minimum value in the array is :20



Thanks for feedback.



Read More....
Check if an array is a min heap
Convert a sorted array into a binary search tree - recursive approach
Print the elements of an array
Find the kth largest element in the array
Find the kth smallest element in the array
Merge two sorted arrays