Link to home
Start Free TrialLog in
Avatar of HenryM2
HenryM2

asked on

Delphi What is the best way to sort an Array of String

What is the fastest sort to alphabetically sort an Array of String.  The arrays will generally be smalish, about 20 elements.  I am using Delphi 2010 and beleve there is a built in function to do this, if so what is the function and how is it used?
Avatar of aflarin
aflarin

You're right. There is a built in function for array of string. But not for dynamic array. It is for TStrings class:

var
  StrArray: TStrings;
begin
  StrArray:= TStringList.Create;
  try
    StrArray.Add( 'Str 1' );
    StrArray.Add( 'Str 2' );
    StrArray.Add( 'Str 3' );
    StrArray.Sort; <------------------------
  finally
    StrArray.Free;
  end;


If you are using D2010, try something like this

TArray.Sort<string>(YourArray , TDelegatedComparer<string>.Construct(
  function(const Left, Right: string): Integer
  begin
    Result := TComparer<String>.Default.Compare(Left, Right);
  end));
Here is tested example:

uses
  Generics.Defaults,
  Generics.Collections;

procedure TForm1.Button1Click(Sender: TObject);
var
  StrArray: array of string;
begin
  SetLength( StrArray, 3);
  StrArray[0]:= 'Str 3';
  StrArray[1]:= 'Str 2';
  StrArray[2]:= 'Str 1';

  TArray.Sort<string>(StrArray , TDelegatedComparer<string>.Construct(
    function(const Left, Right: string): Integer
    begin
      Result := TComparer<String>.Default.Compare(Left, Right);
    end));
end;
ASKER CERTIFIED SOLUTION
Avatar of aflarin
aflarin

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of HenryM2

ASKER

I am having difficulty to get it working.  I have not used TStrings before, is there a Unit to be listes in Uses for this. I added the Uses caluses that you used but get Incompatible type error in line "SetLength( StrArray, 3);"

I also get [DCC Error] SiteDesignerMainUnt.pas(9710): E2250 There is no overloaded version of 'TArray.Sort<System.string>' that can be called with these arguments for line " TArray.Sort<string>(StrArray);"
Avatar of HenryM2

ASKER

Sorry, my previous commnet = false alarm, now working.
Avatar of HenryM2

ASKER

Thanks, works great.