Easy way to add stable sorting to TList and TStringList

后端 未结 4 1714
甜味超标
甜味超标 2021-01-11 18:30

I use TList/TObjectList and TStringList (with associated objects) for a multitude of tasks, either as-is, or as basis for more complex structures. While the sort functionali

4条回答
  •  误落风尘
    2021-01-11 18:33

    From similar question How Can I Replace StringList.Sort with a Stable Sort in Delphi?, linked here in comment by lkessler I need to copy to here really easy trick as mentioned in question.

    You can easily make quick sort behave stable just by adding initial order numbers into data to sort and adding last comparation condition in CustomSort compare function to compare this initial order numbers.

    Easy, fast and smart. Costs only one extra integer (or byte, or use some reserved storage like TComponent.Tag if You sort TComponents) on each sortable item and one initialization loop over them.

    TObjectToSort = class
      ...
      Index: Integer;
    end;
    
    function MyStableSortComparer(List: TStringList; Index1, Index2: Integer): Integer;
    var
      o1, o2: TObjectToSort; 
    begin
      o1 := TObjectToSort(List.Objects[Index1]);
      o2 := TObjectToSort(List.Objects[Index2]);
      ...
      if Result = 0 then
        Result := o1.Index - o2.Index;
    end;
    
    
    for i := 0 to MyStrtingList.Count - 1 do
      TObjectToSort(MyStrtingList.Objects[i]).Index := i;
    MyStrtingList.CustomSort(MyStableSortComparer);
    

提交回复
热议问题