熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Delphi編程 >> 正文

極快的正整數排序函數

2013-11-11 21:04:46  來源: Delphi編程 

  實現原理 對比二進制位

  unit Unit;

  interface

  uses
 Windows Messages SysUtils Variants Classes Graphics Controls Forms
 Dialogs StdCtrls;

  type
 TForm = class(TForm)
  Button: TButton;
  Memo: TMemo;
  procedure ButtonClick(Sender: TObject);
  procedure FormCreate(Sender: TObject);
 end;

  var
 Form: TForm;

  implementation

  {$R *dfm}

  type
 TIntArr = array of Integer;

  {極快的正整數排序函數}
procedure IntSort(arr:TIntArr; low:Integer=; high:Integer=; k:Cardinal=$; c:Cardinal=);
var
 ijx: Integer;
begin
 if high =  then high := Length(arr) ;
 i := low;
 j := high;
 while (i < j) do
 begin
  while (arr[j] and k <> ) and (i < j) do Dec(j);
  while (arr[i] and k = ) and (i < j) do Inc(i);
  if i < j then
  begin
   x := arr[j];
   arr[j] := arr[i];
   arr[i] := x;
  end else begin
   if arr[j] and k <>  then Dec(i) else Inc(j);
   Break;
  end;
 end;
 if k > c then
 begin
  if low < i then IntSort(arr low i k div );
  if j < high then IntSort(arr j high k div );
 end;
end;

  {測試}
procedure TFormButtonClick(Sender: TObject);
var
 MyArr: TIntArr;
 i: Integer;
 t: Int;
begin
 SetLength(MyArr MAXWORD);
 for i := Low(MyArr) to High(MyArr) do MyArr[i] := Random(MaxInt);
 
 t := GetTickCount;
 
 IntSort(MyArr); //調用排序函數
 
 Text := IntToStr(GetTickCount  t);

  MemoClear;
 for i :=  to Length(MyArr) do
 begin
  if i mod  =  then
   MemoLinesAdd(IntToStr(MyArr[i]));
 end;
end;

  procedure TFormFormCreate(Sender: TObject);
begin
 MemoClear;
 MemoAlign := alLeft;
 MemoScrollBars := ssVertical;
end;


From:http://tw.wingwit.com/Article/program/Delphi/201311/8435.html
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.