2011. január 18., kedd

A Delphi implementation of the Shellsort algorithm


Problem/Question/Abstract:

A Delphi implementation of the Shellsort algorithm

Answer:

function FirstLow(var A, B: Str64): Boolean;
begin
  if A < B then
    FirstLow := True
  else
    FirstLow := false;
end;

procedure BinArraySort(Start, Finish: Integer; var Data: PosAry);
var
  StarterKey: Str64;
  Temp: PositionRec; {see remark below}
  Left: Integer;
  Right: Integer;
begin
  Left := Start;
  Right := Finish;
  StarterKey := Data[(Start + Finish) div 2].PBStr;
  repeat
    while FirstLow(Data[Left].PBStr, StarterKey) do
      Left := Left + 1;
    while FirstLow(StarterKey, Data[Right].PBStr) do
      Right := Right - 1;
    if Left <= Right then
    begin
      Temp := Data[Left];
      Data[Left] := Data[Right];
      Data[Right] := Temp;
      Left := Left + 1;
      Right := Right - 1;
    end;
  until
    Right <= Left;
  if Start < Right then
    BinArraySort(Start, Right, Data);
  if Left < Finish then
    BinArraySort(Left, Finish, Data);
end;

Remark:

PositionRec = record
  PBStr: Str64; {key}
  {additional fields}
end;

PosAry = array[1..??] of PositionRec;
PosAryPtr = ^PosAry

is better than just the array itself. Then:

procedure BinArraySort(Start, Finish: Integer; Data: PosAryPtr);

The caller:

var
  PA: PosAryPtr;
begin
  BinArraySort(1, BItems, PA);

Nincsenek megjegyzések:

Megjegyzés küldése