Search code examples
delphidelphi-10.4-sydney

Delphi String Sort


I have a file with very big num like below

45313904626416486480179546360796323469287116537171
465573254230695450538671922463236910370073247307526
5906233480284069039032926795367974774430427486375

How to sort this kind of num ?

The result should be something like (real file is 100000 lines):

5906233480284069039032926795367974774430427486375
45313904626416486480179546360796323469287116537171
465573254230695450538671922463236910370073247307526

I try something with

  MyFlexibleArray := TList<UInt64>.Create;
  AssignFile(F, OpenTextFileDialog1.FileName);
  Reset(F);
  repeat
    Readln(F, str);
    MyFlexibleArray.Add(UInt64(str));
  until EOF(F);
  CloseFile(F);
  MyFlexibleArray.Sort;

With a TStringList, the result wasn't sort in natural way!

Any help will be greatly appreciated.

full file


Solution

  • If you sort your data as a string, the length of the string is not being taken into account.

    If you use a Generic (so you will need System.Generics.Collections in your uses clause) you can specify how to compare objects in a parameter to the constructor. This means that your list of strings would be declared as:

      FMyStrings: TList<String>;
    

    You comparator would compare two strings, if you assume that the strings can only ever contain decimal digits then your comparator would be something like:

      TMyStringSorter = class(TComparer<String>)
      public
        function Compare(const Left, Right: String): Integer; override;
      end;
    
      function TMyStringSorter.Compare(const Left, Right: String): Integer;
      begin
        if(Length(Left)<Length(Right) then Result:=-1
        else if(Length(Right)<Length(Left) then Result:=1
        else Result:=CompareStr(Left, Right);
      end;
    

    Then pass the Interface to the comparer to the TList Constructor and you can sort it according to your own sort algorithm.