mathajax

Maximum value and Index

The java code find a maximum value and its index from array of data
A class Data2 has defined with two member functions named max and maxIndex to find maximum value and its index respectively. 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.


pseudocode of find maximum value

    Read  N integer data  
        

    set  maxvaue = 0 
    
    for n=0 to N-1
 
         check   data[n] > maxvalue
               maxvalue = data[n]
         
    end for   

    print maxvalue

 


pseudocode of find maximum value index

    Read  N integer data  
        
    set mindex  =0
    set  maxvaue = 0 
    
    for n=0 to N-1
 
         check   data[n] > maxvalue
               maxvalue = data[n]
               mindex = n
         
    end for   

    print mindex

 



package cljavabasics;

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

public class  Data2 {

 
 int elem[]; 
 public Data2(int elem[]) {
  this.elem = elem;
 }
 
  
   public  int max() {
  
  int mval = 0; 
  for(int n=0;n<elem.length;n++) 
  {
        if (  elem[n] > mval )
         mval = elem[n];
  }
  return mval;
 }
   
   public  int maxIndex() 
   {  
  int mi = 0;
  int mval = 0;
  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);
    
    
   Data2 data = new Data2(ds);
          int maxval = data.max();
          int maxIndex = data.maxIndex();
       
          System.out.println("nFind a maximum value and its index 
                from "+ " Data array elements");
          
          System.out.println("Random Data :" + Arrays.toString(ds));
   System.out.println("nMaximum value in Data :" + maxval);
   System.out.println("Index of Maximum value in Data :"
                                                      + maxIndex );
       
       
 }

}


Output
Find a maximum 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]

Maximum value in Data :948
Index of Maximum value in Data :1




Comments

Popular posts from this blog

Matrix Forward and Back Substitution

Chebyshev distance between two points

Solve System of Linear Equations by LU Decompose

Complex number Multiplication and Division

Matrix Determinant, Matrix Adjoint and Matrix Inverse