delphilistsortingstable-sort

Easy way to add stable sorting to TList and TStringList


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 functionality is usually good enough, I sometimes need to do a stable sort, and both lists use quicksort.

What's the easiest way to implement stable sorting for TList and/or TStringList? Do I have to write my own sorting routine, or can it be done by using some clever trick with TStringListSortCompare/TListSortCompare?


Solution

  • You'll have to write your own sorting routine.

    You can read the current QuickSort implementation, and write your own stable version (e.g. a Merge sort or any other stable variant).

    Some tricks: