如何在Delphi中用稳定的排序替换StringList.Sort? [英] How Can I Replace StringList.Sort with a Stable Sort in Delphi?
问题描述
我正在做一个简单的StringList.sort,但是Delphi使用的QuickSort并不是稳定的排序,这意味着它可能会用相同的键更改记录的相对顺序.
I'm doing a simple StringList.sort, but Delphi uses a QuickSort that is not a stable sort, meaning it may change the relative order of records with equal keys.
我需要使用一种稳定的排序方式.对我来说,最简单的方法是什么?
I need to use a stable sort. What would be the easiest way for me to implement this?
迈克W的答案可能是最简单的方法,不需要太多的代码更改.
Mike W's answer might be the simplest way to do it without too much code change necessary.
谢谢,迈克.
推荐答案
如果您尚未使用字符串列表的Objects属性,一种快速而又肮脏的解决方案是将原始位置存储在objects属性中作为整数.然后,您可以提供自己的稳定排序比较功能,该功能将原始位置考虑在内.您只需在自己的代码中要做的就是,在调用CustomSort之前,遍历分配对象属性的整个列表:
If you're not already using the Objects property of the string list a quick and dirty solution would be to store the original position in the objects property as an integer. You can then provide your own stable sort compare function that takes the original position into consideration. All you'd have to do in your own code is iterate the entire list assigning the objects property just before calling CustomSort:
function StableSortCompare(List: TStringList; Index1, Index2: Integer): Integer;
begin
result := CompareStr(List[Index1], List[Index2]);
if result = 0 then result := integer(List.Objects[Index1]) - integer(List.Objects[Index2]);
end;
procedure TSortTestForm.SortButtonClick(Sender: TObject);
var
SL : TStringList;
i : integer;
begin
SL := TStringList.Create;
try
SL.AddObject('One', pointer(0));
SL.AddObject('One', pointer(1));
SL.AddObject('One', pointer(2));
SL.AddObject('Two', pointer(3));
SL.AddObject('Two', pointer(4));
SL.AddObject('One', pointer(5));
SL.AddObject('One', pointer(6));
SL.AddObject('One', pointer(7));
// SL.Sort; // Try instead of custom sort to see difference
SL.CustomSort(StableSortCompare);
for i := 0 to SL.Count-1 do begin
Memo1.Lines.Add(Format('Text: %s Orig Pos: %d', [SL[i], integer(SL.Objects[i])]));
end;
finally
SL.Free;
end;
end;
这篇关于如何在Delphi中用稳定的排序替换StringList.Sort?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!