Hallo,
just gestern habe ich es doch mal geschafftm
meine BinSearch fertigzustellen.
Sie arbeitet mit TList, aber abgesehen von der Start-Grenze 0,
sollte es doch auch so klappen.
Das ganze sieht etwas komplizierter aus als Code aus dem Netz,
z.B. das
Delphi-Quellcode:
iCompareResult:= BusinessObject.Compare(
theSearchBusinessObject, theSearchMethod);
Hintergrund ist, dass die BinSearch verschiedene Suchkriterien hat.
Natürlich muss die Liste vorher nach dem jeweiligen Koriteriem sortiert werden.
Das TBusinessObject ist mein Basisobjekt, was eine abstrakte Compare-Methode enthält.
Delphi-Quellcode:
{
name:
InternalBinSearch
usage:
internal bin search method
parameter:
theLow - low order
theHigh - high order
theSearchMethod - search method
return parameter:
return:
NIL, if not found
notes:
}
function TBusinessObjectList.InternalBinSearch(
const theLow, theHigh: Integer;
const theSearchBusinessObject: TBusinessObject;
const theSearchMethod: Integer): TBusinessObject;
var
iMiddle : Integer;
iNewLow : Integer;
iNewHigh : Integer;
iCompareResult : Integer;
BusinessObject : TBusinessObject;
begin
Result:= NIL;
if theLow>theHigh then Exit;
iMiddle:= theLow + ((theHigh-theLow) div 2);
BusinessObject:= Items[iMiddle];
iCompareResult:= BusinessObject.Compare(
theSearchBusinessObject, theSearchMethod);
if iCompareResult=0 then
begin
{ we got it :) }
Result:= BusinessObject;
Exit;
end;
if iCompareResult=-1 then
begin
{ if the current object is smaller than we need
we continue searching at the right side (the higher side) }
iNewLow := iMiddle+1;
iNewHigh := theHigh;
end
else
begin
{ if the current object is smaller than we need
we continue searching at the right side (the higher side) }
iNewLow := theLow;
iNewHigh := iMiddle-1;
end;
Result:= InternalBinSearch(iNewLow, iNewHigh,
theSearchBusinessObject, theSearchMethod);
end; { TBusinessObjectList.InternalBinSearch }
Der Aufruf erfolgt über
Delphi-Quellcode:
{
name:
BinSearch
usage:
internal bin search method
parameter:
theLow - low order
theHigh - high order
theSearchMethod - search method
return parameter:
return:
NIL, if not found
notes:
}
function TBusinessObjectList.BinSearch(
theSearchBusinessObject: TBusinessObject;
const theSearchMethod: Integer): TBusinessObject;
begin
Result:= InternalBinSearch(0, Count-1,
theSearchBusinessObject, theSearchMethod);
end; { TBusinessObjectList.BinSearch }
Heiko