RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TArray.BinarySearch Method (array of T, T, Integer)

Search generic sorted array for an element, using binary search.

Pascal
class function BinarySearch<T>(const Values: array of T; const Item: T; out FoundIndex: Integer; const Comparer: IComparer<T>; Index: Integer; Count: Integer): Boolean; overload;
class function BinarySearch<T>(const Values: array of T; const Item: T; out FoundIndex: Integer; const Comparer: IComparer<T>): Boolean; overload;
class function BinarySearch<T>(const Values: array of T; const Item: T; out FoundIndex: Integer): Boolean; overload;
C++
__fastcall Boolean BinarySearch(const array of T Values, const T Item, int FoundIndex, const IComparer<T> Comparer, int Index, int Count);
__fastcall Boolean BinarySearch(const array of T Values, const T Item, int FoundIndex, const IComparer<T> Comparer);
__fastcall Boolean BinarySearch(const array of T Values, const T Item, int FoundIndex);

The BinarySearch method searches the Values array for the Item element, using binary search.  

BinarySearch returns True if it finds the element and False otherwise. If found, FoundIndex contains the zero-based index of Item. If not found, FoundIndex contains the index of the first entry larger than Item.  

If there is more than one element in the array equal to Item, the index of the first match is returned in FoundIndex. This is the index of any of the matching items, not necessarily of the first item.  

BinarySearch is implemented using an O(log n) search algorithm, for an array with n entries.

Note: BinarySearch requires that the array be sorted.
Note: If the Comparer parameter is provided, it is used to compare elements; otherwise the default comparator for the array elements is used.
 

Delphi Examples: 

 

{
This example demonstrates the usage of TArray's static functions.
The example assumes one memo, one button and one edit box.
}
procedure TForm3.Button1Click(Sender: TObject);
var
  I, FoundIndex: Integer;
  Arr: array of String;
begin
  { Populate an array with the items in the memo }
  SetLength(Arr, InMemo.Lines.Count);

  for I := 0 to InMemo.Lines.Count - 1 do
    Arr[I] := InMemo.Lines[I];

  { Sort the array }
  TArray.Sort<String>(Arr, TStringComparer.Ordinal);

  { Binary search the required value }
  if TArray.BinarySearch<String>(Arr, Edit1.Text, FoundIndex, TStringComparer.Ordinal) then
  begin
    { Element was found. Show a message! }
    MessageDlg('Element "' + Edit1.Text + '" was found in the list!', mtInformation, [mbOK], 0);
  end else
  begin
    { Element was not found. Show a message! }
    MessageDlg('Element "' + Edit1.Text + '" was not found in the list!', mtError, [mbOK], 0);
  end;
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!