Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Sorting your items with control over the sort algorithm

Title: Sorting your items with control over the sort algorithm Question: We need to sort items in a list but we want to adress the objects in the list to do the sort . Answer: Did you ever wanted to sort some lists with your own sorting algoritme? Here some ways of doing just that. In this example we show you how to sort a TList and a TStringList using the objects in it to do the sorting on. Notice the diverence :) We assume you initialized the lists and filled it with TMyObject's type TForm1 = Class(TForm) AListBox : TListBox ; Public StringList: TStringList; MyList : TList ; end; TMyObject = class SomeInt : integer; SomeString : string; end; //For a TList Declare the function like this //TListSortCompare = function (Item1, Item2: Pointer): Integer; function MySort(Item1, Item2: Pointer): Integer; // And for ATStringList // TStringListSortCompare = function(List: TStringList; Index1, Index2: // Integer): Integer; function MyStringListSort (List: TStringList; Index1, Index2: Integer):integer; implementation function MySort(Item1, Item2: Pointer): Integer; begin // Bigger is 1, smaller is -1 and equals is 0 if TMyObject(Item1).SomeInt result := 1 else if TMyObject(Item1).SomeInt TMyObject(Item2).SomeInt then result := -1 else result = 0; end; function MyStringListSort (List: TStringList; Index1, Index2: Integer):integer; begin // Bigger is 1, smaller is -1 and equals is 0 if TMyObject(List.Objects[Item1]).SomeInt [Item2]).SomeInt then result := 1 else if TMyObject(List.Objects[Item1]).SomeInt TMyObject(List.Objects [Item2]).SomeInt then result := -1 else result = 0; end; procedure SomeClick(Sender : TObject); begin // if its a TList you are sorting then do it like this MyList.Sort(MySort) ; // if its a stringlist you are sorting then do it like this StringList.CustomSort(MyStringListSort); //if you want to make it visible then just assign mylist to a Tlistbox.Items AListBox.items.assign(StringList); end;