I need ideas for a simple, lightweight way to get the max and min values of an array of doubles. The trick is I only need the max and min between two indexes in the array.
The built-in arrayOfDoubles.Max() and arrayOfDoubles.Min() will not work, because they check the entire array.
This code will be running constantly and needs to be somewhat efficient. That said, simplicity and readability are more important than speed alone.
Here's one way to get the max and min between two indexes:
double[] array = new double[8] { 3, 1, 15, 5, 11, 9, 13, 7 };
int startIndex = 3;
int endIndex = 6;
// Get max and min between these two indexes in the array
double max = GetMax(array, startIndex, endIndex);
double min = GetMin(array, startIndex, endIndex);
Console.WriteLine("Max = " + max + ", Min = " + min);
Here is the code for GetMax, and GetMin would be very similar:
private static double GetMax(double[] array, int startIndex, int endIndex)
{
double max = double.MinValue;
for (int i = startIndex; i <= endIndex; i++)
{
// Increase max with each bigger value
max = Math.Max(max, array[i]);
}
return max;
}
And the output: Max = 13, Min = 5
The Question: What other ways could I get the same result that might be simpler and wouldn't require too much overhead?