Einzelnen Beitrag anzeigen

Popov
(Gast)

n/a Beiträge
 
#1

Intelligentes BubleSort; sortieren wie im Windows Explorer

  Alt 17. Apr 2012, 01:43
Sortiert man eine Liste wie: "Text 2", "Text 5", "Text 10", ergibt sich alphabetisch folgende Sortierung: "Text 2", "Text 10", "Text 5". Die 10 landet vor der 5, da die 1 der 10 alphabetisch vor der 5 steht. Folgende BubbleSortExtra Funktion sortiert die Liste zuerst alphabetisch, im zweiten Durchgang wird die erste Zahl der Strings nach Wert sortiert
Code:
Text
Text X
Text 1
Text 3
Text 10
Text 20
Text 2
Text 4
Text 5
folgendermaßen
Code:
Text
Text 1
Text 2
Text 3
Text 4
Text 5
Text 10
Text 20
Text X
Auch der Windows-Explorer sortiert seine Daten so.
Delphi-Quellcode:
//Sortiert Liste alphabetisch (beachtet dabei Zahlen nach Wert)
procedure BubbleSortExtra(List: TStrings; NumSort: Boolean = True);

    //Prüft auf Zahl im Strings, wie "Neuer Text (2)". Bei vorhanden sein
    //gibt StrB den Teil vor der Zahl, StrN die Zahl, StrE den Rest.
    function IsNumIn(Str: String; var StrB, StrNum, StrE: String): Boolean;
    var
      k: Integer;
    begin
      StrB := ''; // Text vor Zahl
      StrNum := ''; // Zahl
      StrE := ''; // Text nach Zahl

      k := 1;
      while k <= Length(Str) do
        if Pos(Str[k], '0123456789') = 0 then
        begin
          StrB := StrB + Str[k];
          Inc(k);
        end else Break;

      while k <= Length(Str) do
        if Pos(Str[k], '0123456789') > 0 then
        begin
          StrNum := StrNum + Str[k];
          Inc(k);
        end else Break;

      StrE := Copy(Str, k, Length(Str));
      Result := StrNum <> '';
    end;

var
  i: Integer;
  Done: Boolean;
  IsNum1, IsNum2: Boolean;
  StrTemp: String;
  StrB1, StrNum1, StrE1: String;
  StrB2, StrNum2, StrE2: String;
begin
  repeat //erste Sortierung; Strings nach Alphabet sortieren
    Done := True;
    for i := 0 to List.Count - 2 do
    begin
      if CompareText(List[i], List[i + 1]) > 0 then
      begin
        StrTemp := List[i + 1];
        List[i + 1] := List[i];
        List[i] := StrTemp;
        Done := False;
      end;
    end;
  until Done;

  if not NumSort then Exit;

  repeat //zweitete Sortierung; Strings mit Zahlen nach Höhe sortiert
    Done := True;
    for i := 0 to List.Count - 2 do
    begin
      IsNum1 := IsNumIn(List[i], StrB1, StrNum1, StrE1);
      IsNum2 := IsNumIn(List[i + 1], StrB2, StrNum2, StrE2);

      if (CompareText(StrB1, StrB2) = 0) and (IsNum1 and IsNum2) then
        if StrToIntDef(StrNum1, 0) > StrToIntDef(StrNum2, 0) then
        begin
          StrTemp := List[i + 1];
          List[i + 1] := List[i];
          List[i] := StrTemp;
          Done := False;
        end;
    end;
  until Done;
end; {Popov}
Bei der Sortierung handelt es sich um eine BubbleSort Funktion. Parameter NumSort = False erlaubt auch eine klassische Sortierung.
  Mit Zitat antworten Zitat