RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TArray.Sort Method (array of T)

Sort generic array.

Pascal
class procedure Sort<T>(var Values: array of T); overload;
class procedure Sort<T>(var Values: array of T; const Comparer: IComparer<T>); overload;
class procedure Sort<T>(var Values: array of T; const Comparer: IComparer<T>; Index: Integer; Count: Integer); overload;
C++
__fastcall Sort(array of T Values);
__fastcall Sort(array of T Values, const IComparer<T> Comparer);
__fastcall Sort(array of T Values, const IComparer<T> Comparer, int Index, int Count);

This method sorts the Values generic array, using an O(n log n) operation, where n is the number of elements in the array. The order of equal elements may not be preserved, since a QuickSort algorithm is used.

Note: If the Comparer parameter is provided, it is used to compare elements; otherwise the default comparator for the array elements is used.
 

Delphi Examples: 

 

{
This example demonstrates the usage of TArray's static functions.
The example assumes one memo, one button and one edit box.
}
procedure TForm3.Button1Click(Sender: TObject);
var
  I, FoundIndex: Integer;
  Arr: array of String;
begin
  { Populate an array with the items in the memo }
  SetLength(Arr, InMemo.Lines.Count);

  for I := 0 to InMemo.Lines.Count - 1 do
    Arr[I] := InMemo.Lines[I];

  { Sort the array }
  TArray.Sort<String>(Arr, TStringComparer.Ordinal);

  { Binary search the required value }
  if TArray.BinarySearch<String>(Arr, Edit1.Text, FoundIndex, TStringComparer.Ordinal) then
  begin
    { Element was found. Show a message! }
    MessageDlg('Element "' + Edit1.Text + '" was found in the list!', mtInformation, [mbOK], 0);
  end else
  begin
    { Element was not found. Show a message! }
    MessageDlg('Element "' + Edit1.Text + '" was not found in the list!', mtError, [mbOK], 0);
  end;
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!