Skip to content

Add function to calculate the median of a set of numbers #41

Closed
@delphidabbler

Description

@delphidabbler

There should be different implementations of Median for floating point and integer medians:

function Median(const A: array of Extended): Extended; overload;
begin
  Assert(Length(A) > 0);
  // optimisations for array lengths 1 & 2 to avoid sorting
  if Length(A) = 1 then
    Exit(A[0]);
  if Length(A) = 2 then
    Exit((A[0] + A[1]) / 2.0);
  Generics.Collections.TArray.Sort<Extended>(A); // using standard comparer
  var MiddleLo := Length(A) div 2;
  if Odd(Length(A)) then
    Result := A[MiddleLo + 1]
  else
    Result := (A[MiddleLo] + A[MiddleLo + 1]) / 2.0;
end;

function Median(const A: array of Integer): Extended; overload;
begin
  Assert(Length(A) > 0);
  // optimisations for array lengths 1 & 2 to avoid sorting
  if Length(A) = 1 then
    Exit(A[0]);
  if Length(A) = 2 then
    Exit((A[0] + A[1]) / 2);
  Generics.Collections.TArray.Sort<Integer>(A); // using standard comparer
  var MiddleLo := Length(A) div 2;
  if Odd(Length(A)) then
    Result := A[MiddleLo + 1]
  else
    Result := (A[MiddleLo] + A[MiddleLo + 1]) / 2;
end;

This issue was extracted from issue #16

Metadata

Metadata

Assignees

Labels

completedIssue completed and committed to develop. To be closed on next releaseenhancementNew feature or request

Projects

Status

Completed

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions