问题
I need to sort close to a 1,00,000 floating point entries in Delphi. I am new to Delphi and would like to know if there are any ready made solutions available. I tried a few language provided constructs and they take an inordinate amount of time to run to completion.(a 5-10 sec execution time is fine for the application)
回答1:
why not just implement a quick Sort algorithm?
see this simple code
program ProjectSortFoat;
{$APPTYPE CONSOLE}
uses
SysUtils;
procedure QuickSort(var List: array of Double; iLo, iHi: Integer) ;
var
Lo : integer;
Hi : integer;
T : Double;
Mid : Double;
begin
Lo := iLo;
Hi := iHi;
Mid:= List[(Lo + Hi) div 2];
repeat
while List[Lo] < Mid do Inc(Lo) ;
while List[Hi] > Mid do Dec(Hi) ;
if Lo <= Hi then
begin
T := List[Lo];
List[Lo] := List[Hi];
List[Hi] := T;
Inc(Lo);
Dec(Hi);
end;
until Lo > Hi;
if Hi > iLo then QuickSort(List, iLo, Hi);
if Lo < iHi then QuickSort(List, Lo, iHi);
end;
const
Elements = 1000000;
var
doubleArray : array of Double;
i : integer;
t : TDateTime;
begin
SetLength(doubleArray,Elements);
try
t:=Now;
Writeln('Init Generating '+FormatFloat('#,',Elements)+' random numbers ');
for i:=low(doubleArray) to high(doubleArray) do
doubleArray[i]:=Random(10000000)+Random; //can be improved
Writeln('Elapsed '+FormatDateTime('HH:NN:SS.ZZZ',Now-t));
t:=Now;
Writeln('Sorting '+FormatFloat('#,',Elements)+' random numbers ');
QuickSort(doubleArray, Low(doubleArray), High(doubleArray)) ;
Writeln('Elapsed '+FormatDateTime('HH:NN:SS.ZZZ',Now-t));
finally
Finalize(doubleArray);
end;
Readln;
end.
in my machine, the execution time for sorting 1.000.000 float numbers is 0.167 seconds.
if you have delphi 7 or another older version (i don't know if exist in the new versions) you can check the
C:\Program Files\Borland\Delphi7\Demos\Threads
path, for a cool demo app using differents sorting algorithms an threads.
回答2:
What version are you using? If you're in Delphi 2009 or 2010, you can use generics to make a TList<real>
and call its Sort method.
If you're in an earlier version, the non-generic TList has a Sort method too, but it's a bit trickier to set up since it uses pointers, and Real (or Double), which is what you probably want to use as a floating point number, is too large to cast to a pointer.
来源:https://stackoverflow.com/questions/2485750/delphi-sorted-list