Tips-A2Z home page


Sub-categories

(None)

All  |   Discussion (1)Algorithms

Shell sort: An efficient way to sort up to a couple of hundred items.
Procedure ShellSort(var a: array of Word);

var

bis, i, j, k: LongInt;

h: Word;

begin

bis := High(a);

k := bis shr 1;// div 2

while k > 0 do

begin

for i := 0 to bis - k do

begin

j := i;

while (j >= 0) and (a[j] > a[j + k]) do

begin

h := a[j];

a[j] := a[j + k];

a[j + k] := h;

if j > k then

Dec(j, k)

else

j := 0;

end; // {end while]

end; // { end for}

k := k shr 1; // div 2

end; // {end while}



end;
   Kevin Solway (173)

– –– ——— –– –

Quick sort: Efficient sorting of large numbers of items.
procedure QuickSort(var A: array of Integer; 

iLo, iHi: Integer) ;

var

Lo, Hi, Pivot, T: Integer;

begin

Lo := iLo;

Hi := iHi;

Pivot := A[(Lo + Hi) div 2];

repeat

while A[Lo] < Pivot do Inc(Lo) ;

while A[Hi] > Pivot do Dec(Hi) ;

if Lo <= Hi then

begin

T := A[Lo];

A[Lo] := A[Hi];

A[Hi] := T;

Inc(Lo) ;

Dec(Hi) ;

end;

until Lo > Hi;

if Hi > iLo then QuickSort(A, iLo, Hi) ;

if Lo < iHi then QuickSort(A, Lo, iHi) ;

end;
   Kevin Solway (173)

– –– ——— –– –

Rounding: The built-in round function might not always return the result you want. For example: Round(25.5) = 26, but Round(26.5) = 26.

It is called a "banker's round", and rounds to the nearest even number. For a large number of operations, there is no bias.

The following function will round-up if the fractional part >= 0.5:
function RoundN(x: Extended): LongInt;

begin

Result := Int(X) + Int(Frac(X) * 2);

end;

The following function will round (as per RoundN), but to a certain number of decimal places:
function RoundD(x: Extended; d: Integer): Extended;

// RoundD(123.456, 0) = 123.00

// RoundD(123.456, 2) = 123.46

// RoundD(123456, -3) = 123000

var n: Extended;

begin

n := IntPower(10, d);

x := x * n;

Result := (Int(x) + Int(Frac(x) * 2)) / n;

end;
   Kevin Solway (173)

– –– ——— –– –


 


 

To post a new tip, sign up for a free account.
(Unfortunately this is a necessary spam prevention measure)

Who is online
In total there are 47 users online :: 0 registered and 47 guests (based on users active over the past 5 minutes)