I consider two approaches for calculating the maximum/minimum of an Array.
First:
public class Extrema {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
double[] arr = new double[] { -0.11112, -0.07654, -0.03902, 0.0,
0.03902, 0.07654, 0.11112, 0.14142, 0.1663, 0.18478, 0.19616 };
double max = Double.NEGATIVE_INFINITY;
// Find out maximum value
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
}
}
Second approach would be to pre-sort the array and then get arr[0] as minima and the last entry of te array as maxima.
as i know the fastest sorting-algorithms are 0(n log n). The loop from the first approach will take 0(n) time. But with n comparisons and at worst n writing-operations. Since Time-messurement in java is not really trustable there is a need to formalise this question... I would prefer The first method.. am i right? aspecially if i need both extrema and thus need <=n² writeing-operations. At how many method-calls with the same Array pre-sorting makes sence? best regards, Jan