I have this method which calculates the average, median and percentile information given a long array of numbers. Is there any better and efficient way to do the same?
public static double median(long[] numbers) {
Arrays.sort(numbers, 0, numbers.length);
int middle = numbers.length / 2;
if (numbers.length % 2 == 1) {
return numbers[middle];
} else {
return (numbers[middle - 1] + numbers[middle]) / 2.0;
}
}
public static double average(long[] numbers) {
int sum = 0;
for (long l : numbers)
sum += l;
double average = 1.0d * sum / numbers.length;
return average;
}
public static long[] percentiles(long[] numbers, double... percentiles) {
Arrays.sort(numbers, 0, numbers.length);
long[] values = new long[percentiles.length];
for (int i = 0; i < percentiles.length; i++) {
int index = (int) (percentiles[i] * numbers.length);
values[i] = numbers[index];
}
return values;
}