2009年5月29日

Delphi TStringList QuickSort 排序

在 Form 上放一個 TMemo
在 implementation 區加入 function

// 字串反排
function DescCompareStrings(List: TStringList; Index1, Index2: Integer): Integer;
begin
Result := - AnsiCompareText(List[Index1], List[Index2]);
end;

// 在 FormCreate 事件中加入

procedure TForm1.FormCreate(Sender: TObject);
var
StringList: TStringList;
begin
StringList := TStringList.Create;
try
with StringList do
begin
Add('3');
Add('7');
Add('1');
Add('9');
Add('5');
end;

StringList.Sort; // 正排 會使用 QuickSort 來排序
Memo1.Lines := StringList; // 印到 Memo1

StringList.CustomSort(DescCompareStrings); // 使用反排 function
// CustomSort 會使用 QuickSort 來排序
Memo1.Lines.AddStrings(StringList); // 加到 Memo1
finally
StringList.Free;
end;
end;

{ Memo1

1
3
5
7
9
9
7
5
3
1

}

沒有留言:

網誌存檔