Mirror

How to sort a TList (Views: 26)


Problem/Question/Abstract:

How to sort a TList

Answer:

procedure BubbleSort(const List: TList; const Compare: TListSortCompare);
var
  Limit: Integer;
  I: Integer;
  Temp: Pointer;
  Swapped: Boolean;
begin
  for Limit := (List.Count - 1) downto 1 do
  begin
    Swapped := False;
    for I := 0 to (Limit - 1) do
      if (Compare(List[I], List[I + 1]) > 0) then
      begin
        Temp := List[I];
        List[I] := List[I + 1];
        List[I + 1] := Temp;
        Swapped := True;
      end;
    if (not Swapped) then
      Break;
  end;
end;

procedure InsertionSort(const List: TList; const Compare: TListSortCompare);
var
  Step: Integer;
  Temp: Pointer;
  I: Integer;
begin
  for Step := 1 to (List.Count - 1) do
  begin
    Temp := List[Step];
    for I := (Step - 1) downto 0 do
      if (Compare(List[I], Temp) > 0) then
        List[I + 1] := List[I]
      else
        Break;
    List[I + 1] := Temp;
  end;
end;

procedure ShellSort(const List: TList; const Compare: TListSortCompare);
var
  Step: Integer;
  H: Integer;
  I: Integer;
  Temp: Pointer;
begin
  H := 1;
  while (H <= (List.Count div 9)) do
    H := 3 * H + 1;
  while (H > 0) do
  begin
    for Step := H to (List.Count - 1) do
    begin
      Temp := List[Step];
      I := Step - H;
      while (I >= 0) do

      begin
        if (Compare(Temp, List[I]) < 0) then
          List[I + H] := List[I]
        else
          Break;
        Dec(I, H);
      end;
      List[I + H] := Temp;
    end;
    H := H div 3;
  end;
end;

procedure QuickSort1(const List: TList; const Compare: TListSortCompare;
  const L: Integer; const R: Integer);
var
  I: Integer;
  J: Integer;
  Temp: Pointer;
begin
  I := L - 1;
  J := R;
  repeat
    Inc(I);
    while (Compare(List[I], List[R]) < 0) do
      Inc(I);
    Dec(J);
    while (J > 0) do
    begin
      Dec(J);
      if (Compare(List[J], List[R]) <= 0) then
        Break;
    end;
    if (I >= J) then
      Break;
    Temp := List[I];
    List[I] := List[J];
    List[J] := Temp;
  until
    (False);
  Temp := List[I];
  List[I] := List[R];
  List[R] := Temp;
end;

procedure QuickSort(const List: TList; const Compare: TListSortCompare);
begin
  QuickSort1(List, Compare, 0, List.Count - 1);
end;

<< Back to main page