# Board index » delphi » Sorting Array Of String

## Sorting Array Of String

Hi!

Does anyone have a idea how to sort array which is full of strings to the
alphabetical order?

Example source would be nice ;)

Thanks!

Regards
WarL...@Sci.Fi

## Re:Sorting Array Of String

##### Quote
In article <7006u6\$ko...@tron.sci.fi>, "Spoogy" <warl...@sci.fi> writes:
>Does anyone have a idea how to sort array which is full of strings to the
>alphabetical order?

Copy to sorted TStringList, copy back to array :-

var
TempSort : TStringList;
i : integer;
begin
TempSort := TStringList.Create;
TempSort.Sorted := true;
for i := 0 to high(MyArray) do
for i := 0 to high(MyArray) do
MyArray[i] := TempSort.Strings[i];
TempSort.Free;
end;

Alan Lloyd
alangll...@aol.com

## Re:Sorting Array Of String

##### Quote
In article <7006u6\$ko...@tron.sci.fi>, "Spoogy" <warl...@sci.fi> writes:
>Does anyone have a idea how to sort array which is full of strings to the
>alphabetical order?

Copy to sorted TStringList, copy back to array :-

var
TempSort : TStringList;
i : integer;
begin
TempSort := TStringList.Create;
TempSort.Sorted := true;
for i := 0 to high(MyArray) do
for i := 0 to high(MyArray) do
MyArray[i] := TempSort.Strings[i];
TempSort.Free;
end;

Alan Lloyd
alangll...@aol.com

## Re:Sorting Array Of String

Spoogy schrieb:

##### Quote

> Hi!

> Does anyone have a idea how to sort array which is full of strings to the
> alphabetical order?

The sort using a TStringList is fine, but if the data is in an array,
it's a waste of resources to copy it to a stringlist first. An easy sort
routine:

{ For the understanding of this routine, it is helpful to visualize an
array in a single line:

Index ->         1      2      3      4     5
Content ->       Paul   Linda  Ringo  John  Anna

##### Quote
}

procedure SortTheArray ;
var
imin: integer ;
i, j: integer ;
SaveVal:  string ;
begin
for i := 1 to MAX do
begin

{ assume the current is the lowest }
imin := i ;

{ test all "to the right", if they are lower }
for j := i to MAX do
begin
{ if we find one which is lower than the current,
we save that index }
if array[ j ] < array[ imin ] then
imin := j ;
end ;

{ if we found a new "lowest", we change the values
at Index i and imin }
if i <> imin then
begin
SaveVal := array[ imin ] ;
array[ imin ] := array[ i ] ;
array[ i ] := SaveVal ;
end ;
end ;
end ;

By changing the "<" with a ">", you reverse the sort order.

Matthias

--
___________________________________________________________
le...@codelab.ch             42              Matthias Leisi

All SPAM sent to this address is reported and posted