Mega Code Archive

 
Categories / Delphi / Algorithm Math
 

Binair search

Title: Binair search Question: howto search for the index of an integer in a sorted array? Answer: This little algorithm is simple and amizingly fast!!! You can use this one togetter with one of the sorting algorithms in the delphi samples directory usage copy and paste this function into your code and the first parameter will represent the array where you want to search in the second is the value you would like to search for. The result is the index of the key in the array or -1 if the key isn't found. function BinSearch(A: array of integer; Key : Integer): Integer; var i, step : integer; begin i := Round(Length(a) / 2); step := round(i / 2); if a[0] = key then i := 0; While (step 0)and(a[i] key) do begin if a[i] step := Round(step / 2); end; if a[i] = key then result := i Else Result := -1; end;