This is a new site that's currently running on alpha code. There are going to be bugs. If you discover any, please report them on the site's issues page (GitHub account required). Thanks.
Warning: Many URLs are going to change. Refer to the README file to discover which library project's documentation has been completed.
Project: Array Utilities Unit
Unit: DelphiDabbler.Lib.ArrayUtils
Record: TArrayUtils
Applies to: ~>0.1
class procedure Sort<T>(var A: array of T; const AComparer: TComparison<T>);
overload; static;
class procedure Sort<T>(var A: array of T; const AComparer: IComparer<T>);
overload; static;
class procedure Sort<T>(var A: array of T);
overload; static;
Sorts an array in place.
Parameters:
A - The array being sorted. The array to be sorted is passed in and the sorted array is passed out
AComparer - An optional function or object that can be used to compare two values. Determines the sort order of the array.
If AComparer is provided it must be one of:
If this parameter is omitted then the default comparer defined by the TComparer<T>.Default method from the Delphi’s System.Generics.Defaults unit is used.
The first example uses an equality comparer function to reverse sort an array of integers.
procedure Sort_Eg1;
var
A, Expected: TArray<Integer>;
ReverseComparerFn: TComparison<Integer>;
begin
ReverseComparerFn := function(const Left, Right: Integer): Integer
begin
Result := Right - Left;
end;
A := TArray<Integer>.Create(1, 2, 3, 4, 2, 3, 2);
TArrayUtils.Sort<Integer>(A, ReverseComparerFn);
Expected := TArray<Integer>.Create(4, 3, 3, 2, 2, 2, 1);
Assert(TArrayUtils.Equal<Integer>(Expected, A));
end;
The second example uses an equality comparer object to sort an array of strings.
procedure Sort_Eg2;
var
A, Expected: TArray<string>;
ComparerObj: IComparer<string>;
begin
ComparerObj := TDelegatedComparer<string>.Create(
function (const Left, Right: string): Integer
begin
Result := CompareStr(Left, Right);
end
);
A := TArray<string>.Create(
'dave', 'dee', 'dozy', 'beaky', 'mick', 'and', 'titch'
);
TArrayUtils.Sort<string>(A, ComparerObj);
Expected := TArray<string>.Create(
'and', 'beaky', 'dave', 'dee', 'dozy', 'mick', 'titch'
);
Assert(TArrayUtils.Equal<string>(Expected, A, SameStr));
end;