mathajax

Minimum value and Index

The java code find a minimum value and its index from array of data
A class Data has defined with two member functions named min and minIndex to find minimum value and its index. A object is created to the class Data with array of integers which are randomly generated from random object. The random generated integer values limited to 1000.
Data are generated from randomly using java Random class


pseudocode of find minimum value

    Read  N integer data  
        

    set  minvaue = MAX 
    
    for n=0 to N-1
 
         check   data[n] < minvalue
               minvalue = data[n]
         
    end for   

    print minvalue

 


pseudocode of find minimum value index

    Read  N integer data  
        
    set mindex  =0
    set  minvaue = MAX 
    
    for n=0 to N-1
 
         check   data[n] < minvalue
               minvalue = data[n]
               mindex = n
         
    end for   

    print mindex

 




import java.util.Arrays;
import java.util.Random;

public class  Data {

 
 int elem[]; 
 public Data(int elem[]) {
  this.elem = elem;
 }
 
  
   public  int min() {
  
  int mval = Integer.MAX_VALUE; 
  for(int n=0;n<elem.length;n++) 
  {
        if (  elem[n] < mval )
         mval = elem[n];
  }
  return mval;
 }
   
   public  int minIndex() 
   {  
  int mi = 0;
  int mval = Integer.MAX_VALUE;
  for(int n=0;n<elem.length;n++) 
  {
        if (  elem[n] < mval ) {
         mval = elem[n];
         mi=n;
        }
         
  }
  return mi;
 }
   
   

 public static void main(String[] args) 
 {
    int dsize=20;
    int ds[] =new int[dsize];
    
    Random rd =new Random();
    rd.setSeed(0);
    
       for(int n=0; n<dsize ; n++)
  ds[n] = rd .nextInt(1000);
    
    
    Data data = new Data(ds);
          double minval = data.min();
          double minIndex = data.minIndex();
       
          System.out.println("\nFind a minimum value and its index 
              from " + " Data array elements");
          
          System.out.println("Random Data :" + Arrays.toString(ds));
   System.out.println("\nMinimum value in Data :" + minval);
   System.out.println("Index of Minimum value 
                                        in Data :" + minIndex );
       
       
 }

}


Output
Find a minimum value and its index from Data, array elements

Random Data :[360, 948, 29, 447, 515, 53, 491, 761, 
   719, 854, 77, 677, 473, 262, 95, 844, 84, 875, 241, 320]

Minimum value in Data :29.0
Index of Minimum value in Data :2.0




Comments

Popular posts from this blog

Solving System of Linear Equations by Gauss Jordan Elimination

Matrix Forward and Back Substitution

Solve System of Linear Equations by LU Decompose

Matrix Determinant by Upper Triangular Matrix

Chebyshev distance between two points