12.02.2015, 22:16
|
|
Sir Richard Abramson
|
|
Регистрация: 05.04.2008
Сообщения: 5,505
Версия Delphi: XE10
Репутация: выкл
|
|
http://www.swissdelphicenter.ch/torr...de.php?id=1916
Код:
function BinSearch(Strings: TStringArray; SubStr: string): Integer;
var
First: Integer;
Last: Integer;
Pivot: Integer;
Found: Boolean;
begin
First := Low(Strings); //Sets the first item of the range
Last := High(Strings); //Sets the last item of the range
Found := False; //Initializes the Found flag (Not found yet)
Result := -1; //Initializes the Result
//If First > Last then the searched item doesn't exist
//If the item is found the loop will stop
while (First <= Last) and (not Found) do
begin
//Gets the middle of the selected range
Pivot := (First + Last) div 2;
//Compares the String in the middle with the searched one
if Strings[Pivot] = SubStr then
begin
Found := True;
Result := Pivot;
end
//If the Item in the middle has a bigger value than
//the searched item, then select the first half
else if Strings[Pivot] > SubStr then
Last := Pivot - 1
//else select the second half
else
First := Pivot + 1;
end;
end;
|