I have a multidimensional array similar to the one described below:
Matrix => array(
[0] => array( [0] => 7, [1] => 'hello' ),
[1] => array( [0] => 3, [1] => 'there' ),
[2] => array( [0] => 1, [1] => 'world' ),
)
What I'm trying to achieve is to sort this array using the values of Matrix[i][0]. What would be the most efficient way to do this? I looked into the recursive QuickSort function possibility, but it's rather complicated as I'm multidimensional arrays. There are many examples of quicksort, but none of them handle taking an "Array of Array of String" as an input.
Please ask for clarification if my text seems gibberish. I'm still fairly new to Delphi.
As Rob pointed out in his comment, there's no way to have an multi-dimensional array that stores both integers and strings (without resorting to variants).
If it's really just an array containing integer/string pairs, it would be much easier to store them in a TStringList
using the Strings
and Objects
properties, and then use CustomSort
to sort on the Object
values:
program Project2;
{$APPTYPE CONSOLE}
uses
SysUtils, Classes;
function MySortProc(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := Integer(List.Objects[Index1]) - Integer(List.Objects[Index2]);
end;
var
SL: TStringList;
i: Integer;
begin
SL := TStringList.Create;
try
for i := 0 to 10 do
SL.AddObject(Format('Item %d', [i]), TObject(Random(i)));
SL.CustomSort(@MySortProc);
for i := 0 to SL.Count - 1 do
WriteLn(Format('%d: %s', [Integer(SL.Objects[i]), SL[i]]));
ReadLn;
finally
SL.Free;
end;
end.
This produces