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.

CopySorted<T> class method

Project: Array Utilities Unit

Unit: DelphiDabbler.Lib.ArrayUtils

Record: TArrayUtils

Applies to: ~>0.1

class function CopySorted<T>(const A: array of T;
  const AComparer: TComparison<T>): TArray<T>;
  overload; static;

class function CopySorted<T>(const A: array of T;
  const AComparer: IComparer<T>): TArray<T>;
  overload; static;

class function CopySorted<T>(const A: array of T): TArray<T>;
  overload; static;

Description

Returns a sorted copy of an array.

The copy is a shallow copy, so any references within the resulting array are the same as those in the initial array.

Parameters:

Returns:

Note

If a deep copy of the sorted array is required then pass the return value of CopySorted<T> to the deep copying overload of Copy<T> along with a suitable TCloner<T> implementation.

Examples

Example #1

The first example uses a comparer function to reverse sort an array of integers.

procedure CopySorted_Eg1;
var
  A, Got, Expected: TArray<Integer>;
  ReverseComparerFn: TComparison<Integer>;
begin
  A := TArray<Integer>.Create(1, 2, 3, 4, 2, 3, 2);
  ReverseComparerFn := function(const Left, Right: Integer): Integer
    begin
      // reverse sort
      Result := Right - Left;
    end;
  Got := TArrayUtils.CopySorted<Integer>(A, ReverseComparerFn);
  Expected := TArray<Integer>.Create(4, 3, 3, 2, 2, 2, 1);
  Assert(TArrayUtils.Equal<Integer>(Expected, Got));
end;

Example #2

The second example uses a comparer object to sort an array of strings.

procedure CopySorted_Eg2;
var
  A, Got, 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'
  );
  Got := TArrayUtils.CopySorted<string>(A, ComparerObj);
  Expected := TArray<string>.Create(
    'and', 'beaky', 'dave', 'dee', 'dozy', 'mick', 'titch'
  );
  Assert(TArrayUtils.Equal<string>(Expected, Got, SameStr));
end;

See Also