Search code examples
sortingdelphiinsertiontstringlist

Insertion Sort - TStringList Delphi


i'm trying to sort TStringList of integers from a text file with Insertion and Selection Sort .Selection Sort works ok , but the Insertion Sort doesnt work with my code . Can someone tell me where i'm wrong ? My 'numbers.txt' has 5000 lines of numbers. Thanks in advance

UPDATE : I have edited my code a bit , it works now with Insertion-Sort but it sorts just 4 indexes of integer as on the image

var
  i, Position, n: integer;
  Value: string;
begin
  n := Items.Count;
  for i := 1 to n - 1 do
  begin
    Value := Items[i];
    Position := i-1;
     while (Position >0) and (Items[Position]>Value) do
      begin
        Items[Position+1]:= Items[Position]  ;
        Position := Position -1 ;
        end;
        Items[Position+1] := Value;
  end;
end;

image


Solution

  • Your data in the image is sorting exactly as it should, because you're sorting on string values, and based on the comparison you're making the order is perfect. "1143" falls exactly between the string values "11413" and "11443", because the comparison is made character by character out to the length of the shortest of the values. "1141" < "1143" < "1144", based on the first four characters of each string.

    If you want an actual integer sort, then you need to convert the two values to integer before comparing them. Something like this should work (note I did not test your overall sort logic - I just used values that demonstrate the concept):

    program Project1;
    
    {$APPTYPE CONSOLE}
    
    {$R *.res}
    
    uses
      System.SysUtils, System.Classes;
    
    var
      i, Position, n: integer;
      Value: integer;
      Items: TStringList;
    begin
      Items := TStringList.Create;
      try
        Items.DelimitedText := '1116,11170,11178,11206,1122,11221,11228';
        n := Items.Count;
        for i := 1 to n - 1 do
        begin
          Value := StrToInt(Items[i]);
          Position := i - 1;
           while (Position > 0) and (StrToInt(Items[Position]) > Value) do
            begin
              Items[Position + 1]:= Items[Position];
              Position := Position - 1 ;
            end;
            Items[Position+1] := IntToStr(Value);
        end;
        for i := 0 to Items.Count - 1 do
          WriteLn(Items[i]);
      finally
        Items.Free;
      end;
      ReadLn;
    end.
    

    The output I got from the code above in a console window:

    1116
    1122
    11170
    11178
    11206
    11221
    11228