Title: Impementing UnQuickSort in Delphi - How to Use the TListSortCompare function
In the How to Randomize / Shuffle Collections and Lists article you can locate a custom Delphi function: Shuffle. Shuffle is a randomizing function that takes a TList type of object and "sorts" the items in the list in a random order - thus making the list randomized.
Rawlyn, a member of the Delphi Programming Forum has a different interesting idea how to randomize the items of a Delphi list (or collection) - by sorting!
Sort, but sort randomly!
The TList Delphi class exposes the Sort method. Sort performs a QuickSort on the list based on the comparison function Compare.
Here's the declaration of the TList.Sort method:
procedure Sort(Compare: TListSortCompare) ;
The TListSortCompare is actually a function type, declared as:
TListSortCompare = function (Item1, Item2: Pointer): Integer;
Thus, the Compare parameter of the Sort method is actually a function - Sort method takes a function as a parameter.
The TListSortCompare is a function you write that indicates how the items are to be ordered. It should return
a positive value if Item1 is less than (0 if they are equal,
a negative value if Item1 is greater than () Item2.
With the above in mind, here's an implementation of the TListSortCompare that will actually result in a randomized list.
function UnSort(Item1, item2: Pointer): integer;
begin
result := -1 + Random(3);
end;
Random is a RTL function which returns a randomly generated number within a specified range. When MaxValue is specified the random number returned falls between 0 and MaxValue.
Using "-1 + Random(3)" we ensure that -1, 0 or 1 are the only possible values to be returned.
When -1 , 0 or 1 is "applied" as the result of the Sort method, randonmly - we have a randomizer function!
Here's an example of usage:
var
list: TList;
begin
list := TList.Create;
try
// ** add items to the list here
Randomize;
list.Sort(UnSort) ;
// ** list is randomized now
finally
FreeAndNil(List) ;
end,
end;
Note: if you actually want to sort the items in a list holding, let's say, instances of TDeveloper by a developer name - you can use the CompareText function to compares two strings without case sensitivity.