Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to get the minimum or maximum value from an Array of numbers?

Let's say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2]

What is the best way to find the minimum or maximum value in that Array?

Right now, to get the maximum, I am looping through the Array, and resetting a variable to the value if it is greater than the existing value:

var myArray:Array /* of Number */ = [2,3,3,4,2,2,5,6,7,2];  var maxValue:Number = 0;  for each (var num:Number in myArray) {     if (num > maxValue)         maxValue = num; } 

This just doesn't seem like the best performing way to do this (I try to avoid loops whenever possible).

like image 332
Eric Belair Avatar asked Jan 08 '09 15:01

Eric Belair


People also ask

How do you find the minimum of an array?

M = min( A ) returns the minimum elements of an array. If A is a vector, then min(A) returns the minimum of A . If A is a matrix, then min(A) is a row vector containing the minimum value of each column of A .

How do you find the maximum and minimum of an array in C++?

Using min_element() with max_element() function C++ standard library also provides individual functions min_element() and max_element() to find smallest and largest elements in array, respectively. That's all about finding the minimum and maximum values in an array in C++.


1 Answers

The theoretical answers from everyone else are all neat, but let's be pragmatic. ActionScript provides the tools you need so that you don't even have to write a loop in this case!

First, note that Math.min() and Math.max() can take any number of arguments. Also, it's important to understand the apply() method available to Function objects. It allows you to pass arguments to the function using an Array. Let's take advantage of both:

var myArray:Array = [2,3,3,4,2,2,5,6,7,2]; var maxValue:Number = Math.max.apply(null, myArray); var minValue:Number = Math.min.apply(null, myArray); 

Here's the best part: the "loop" is actually run using native code (inside Flash Player), so it's faster than searching for the minimum or maximum value using a pure ActionScript loop.

like image 64
Josh Tynjala Avatar answered Oct 12 '22 18:10

Josh Tynjala