Author: Tomas Rutkauskas How to sort a TList Answer: 1 procedure BubbleSort(const List: TList; const Compare: TListSortCompare); 2 var 3 Limit: Integer; 4 I: Integer; 5 Temp: Pointer; 6 Swapped: Boolean; 7 begin 8 for Limit := (List.Count - 1) downto 1 do 9 begin 10 Swapped := False; 11 for I := 0 to (Limit - 1) do 12 if (Compare(List[I], List[I + 1]) > 0) then 13 begin 14 Temp := List[I]; 15 List[I] := List[I + 1]; 16 List[I + 1] := Temp; 17 Swapped := True; 18 end; 19 if (not Swapped) then 20 Break; 21 end; 22 end; 23 24 procedure InsertionSort(const List: TList; const Compare: TListSortCompare); 25 var 26 Step: Integer; 27 Temp: Pointer; 28 I: Integer; 29 begin 30 for Step := 1 to (List.Count - 1) do 31 begin 32 Temp := List[Step]; 33 for I := (Step - 1) downto 0 do 34 if (Compare(List[I], Temp) > 0) then 35 List[I + 1] := List[I] 36 else 37 Break; 38 List[I + 1] := Temp; 39 end; 40 end; 41 42 procedure ShellSort(const List: TList; const Compare: TListSortCompare); 43 var 44 Step: Integer; 45 H: Integer; 46 I: Integer; 47 Temp: Pointer; 48 begin 49 H := 1; 50 while (H <= (List.Count div 9)) do 51 H := 3 * H + 1; 52 while (H > 0) do 53 begin 54 for Step := H to (List.Count - 1) do 55 begin 56 Temp := List[Step]; 57 I := Step - H; 58 while (I >= 0) do 59 60 begin 61 if (Compare(Temp, List[I]) < 0) then 62 List[I + H] := List[I] 63 else 64 Break; 65 Dec(I, H); 66 end; 67 List[I + H] := Temp; 68 end; 69 H := H div 3; 70 end; 71 end; 72 73 procedure QuickSort1(const List: TList; const Compare: TListSortCompare; 74 const L: Integer; const R: Integer); 75 var 76 I: Integer; 77 J: Integer; 78 Temp: Pointer; 79 begin 80 I := L - 1; 81 J := R; 82 repeat 83 Inc(I); 84 while (Compare(List[I], List[R]) < 0) do 85 Inc(I); 86 Dec(J); 87 while (J > 0) do 88 begin 89 Dec(J); 90 if (Compare(List[J], List[R]) <= 0) then 91 Break; 92 end; 93 if (I >= J) then 94 Break; 95 Temp := List[I]; 96 List[I] := List[J]; 97 List[J] := Temp; 98 until 99 (False); 100 Temp := List[I]; 101 List[I] := List[R]; 102 List[R] := Temp; 103 end; 104 105 procedure QuickSort(const List: TList; const Compare: TListSortCompare); 106 begin 107 QuickSort1(List, Compare, 0, List.Count - 1); 108 end;