median function

double? median(
  1. Iterable<num> values
)

Returns the median of values, or null if the collection is empty.

For an even count, returns the average of the two middle values. Does not mutate the caller's input.

Example:

median([3, 1, 2]); // 2.0
median([4, 1, 2, 3]); // 2.5

Audited: 2026-06-12 11:26 EDT

Implementation

double? median(Iterable<num> values) {
  final List<double> list = values.map((num n) => n.toDouble()).toList()..sort();
  if (list.isEmpty) return null;
  final int mid = list.length ~/ 2;
  if (list.length.isOdd) return list[mid];
  return (list[mid - 1] + list[mid]) / 2;
}