Java program to find Maximum and minimum element’s position in a list


To find the maximum and minimum element’s position in a list, the Java program is as follows −

Example

 Live Demo

import java.util.*;
import java.util.Arrays;
import java.util.Collections;
public class Demo{
   public static int index_val(int my_arr[], int t){
      if (my_arr == null){
         return -1;
      }
      int len = my_arr.length;
      int i = 0;
      while (i < len){
         if (my_arr[i] == t){
            return i;
         } else {
            i = i + 1;
         }
      }
      return -1;
   }
   public static void main(String[] args){
      Integer[] my_arr = { 34, 67, 89, 99, 45, 77 };
      int[] my_int_arr = { 34, 67, 89, 99, 45, 77 };
      int min_val = Collections.min(Arrays.asList(my_arr));
      int max_val = Collections.max(Arrays.asList(my_arr));
      System.out.println("The minimum value in the array is : " + min_val);
      System.out.println("The maximum value in the array is : " + max_val);
      System.out.println("The position of the minimum value is: " + index_val(my_int_arr, min_val));
      System.out.println("The position of the maximum value is: " + index_val(my_int_arr, max_val));
   }
}

Output

The minimum value in the array is : 34
The maximum value in the array is : 99
The position of the minimum value is: 0
The position of the maximum value is: 3

A class named Demo defines a linear search function that looks for the index of an element that is specified in the parameter. The main function defines an array and finds the minimum and maximum values from the array. The linear search function is called on this array and the minimum value and the maximum value are also passed as parameters to the linear search function. This will give the index of the minimum and the maximum values of the array.

Updated on: 07-Jul-2020

297 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements