File tree 3 files changed +62
-0
lines changed
3 files changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ function Median(A: array of Double): Double; overload;
2
+ var
3
+ MiddleLo: Integer;
4
+ begin
5
+ if System.Length(A) = 0 then
6
+ raise SysUtils.EArgumentException.Create('Array is empty');
7
+ // optimisations for array lengths 1 & 2 to avoid sorting
8
+ if System.Length(A) = 1 then
9
+ Exit(A[0]);
10
+ if System.Length(A) = 2 then
11
+ Exit((A[0] + A[1]) / 2.0);
12
+ Generics.Collections.TArray.Sort<Double>(A); // using standard comparer
13
+ MiddleLo := System.Length(A) div 2 - 1;
14
+ if System.Odd(System.Length(A)) then
15
+ Result := A[MiddleLo + 1]
16
+ else
17
+ Result := (A[MiddleLo] + A[MiddleLo + 1]) / 2.0;
18
+ end;
Original file line number Diff line number Diff line change
1
+ function Median(A: array of Integer): Double; overload;
2
+ var
3
+ MiddleLo: Integer;
4
+ begin
5
+ if System.Length(A) = 0 then
6
+ raise SysUtils.EArgumentException.Create('Array is empty');
7
+ // optimisations for array lengths 1 & 2 to avoid sorting
8
+ if System.Length(A) = 1 then
9
+ Exit(A[0]);
10
+ if System.Length(A) = 2 then
11
+ Exit((A[0] + A[1]) / 2);
12
+ Generics.Collections.TArray.Sort<Integer>(A); // using standard comparer
13
+ MiddleLo := System.Length(A) div 2 - 1;
14
+ if System.Odd(Length(A)) then
15
+ Result := A[MiddleLo + 1]
16
+ else
17
+ Result := (A[MiddleLo] + A[MiddleLo + 1]) / 2;
18
+ end;
Original file line number Diff line number Diff line change @@ -1871,3 +1871,29 @@ AdvancedTest.URL="https://github.com/delphidabbler/code-snippets/tree/master/tes
1871
1871
Snip =664.dat
1872
1872
DelphiXE =Y
1873
1873
Delphi12A =Y
1874
+
1875
+ [Median_Double]
1876
+ DisplayName =" Median (Double overload)"
1877
+ DescEx =" <p>Returns the median of an array of floating point values.</p><p>Raises an <var>EArgumentException</var> exception if the array is empty.</p>"
1878
+ Kind =routine
1879
+ Units =SysUtils,Generics.Collections
1880
+ SeeAlso =Median_Integer
1881
+ TestInfo =advanced
1882
+ AdvancedTest.Level =unit-tests
1883
+ AdvancedTest.URL =" https://github.com/delphidabbler/code-snippets/tree/master/tests/Cat-Maths"
1884
+ Snip =665.dat
1885
+ DelphiXE =Y
1886
+ Delphi12A =Y
1887
+
1888
+ [Median_Integer]
1889
+ DisplayName =" Median (Integer overload)"
1890
+ DescEx =" <p>Returns the median of an array of integer values.</p><p>Raises an <var>EArgumentException</var> exception if the array is empty.</p>"
1891
+ Kind =routine
1892
+ Units =SysUtils,Generics.Collections
1893
+ SeeAlso =Median_Double
1894
+ TestInfo =advanced
1895
+ AdvancedTest.Level =unit-tests
1896
+ AdvancedTest.URL =" https://github.com/delphidabbler/code-snippets/tree/master/tests/Cat-Maths"
1897
+ Snip =666.dat
1898
+ DelphiXE =Y
1899
+ Delphi12A =Y
You can’t perform that action at this time.
0 commit comments