FAQ
Cover
This is the archive Discourse for the Processing (ALPHA) software.
Please visit the new Processing forum for current information.

   Processing 1.0 _ALPHA_
   Topics & Contributions
   Tools
(Moderator: REAS)
   Finding the largest value of an array
« Previous topic | Next topic »

Pages: 1 
   Author  Topic: Finding the largest value of an array  (Read 1834 times)
REAS


WWW
Finding the largest value of an array
« on: Oct 31st, 2002, 12:52am »

// The maxVal() method returns the largest value of an array  
 
int[] numbers = { 90, 150, 30 };  
 
void loop()  
{  
  int largestNum = maxVal(numbers);  
  println(largestNum);  
}  
 
int maxVal(int[] testArray)  
{  
  int maximum = Integer.MIN_VALUE; //initialize to the smallest int  
  for(int i=0; i<testArray.length; i++) {  
    maximum = max(testArray[i], maximum);  
  }  
  return maximum;  
}  
 
 
/** An alternative maxVal() method, faster  
 
int maxVal(int[] testArray)  
{  
  int maximum = Integer.MIN_VALUE; //initialize to the smallest int  
  for(int i=0; i<testArray.length; i++) {  
    if (testArray[i] > maximum) {  
 maximum = testArray[i];  
    }  
  }  
  return maximum;  
}  
 
*/  
 
fry

WWW
Re: Finding the largest value of an array
« Reply #1 on: Oct 31st, 2002, 4:06am »

and if you really wanna be a weenie, this one is (just slightly) improved:
 
 
int maxVal(int[] testArray)    
{  
  // initialize to the first element, since that's  
  // what will be assigned the first time through  
  // the loop anyways, in the previous version
  int maximum = testArray[0];
 
  // then start the loop at 1 instead of 0, because
  // the 0th element has already been 'checked'
  for(int i = 1; i < testArray.length; i++) {  
    if (testArray[i] > maximum) {  
 maximum = testArray[i];  
    }  
  }
  return maximum;  
}
 
Pages: 1 

« Previous topic | Next topic »