Welcome to the new DelphiDabbler Code Library Documentation.

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.

Sort<T> class method

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;

Description

Sorts an array in place.

Parameters:

Examples

Example #1

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;

Example #2

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;

See Also