This documentation is archived and is not being maintained.

ArrayList.BinarySearch Method (Object)

.NET Framework 1.1

Searches the entire sorted ArrayList for an element using the default comparer and returns the zero-based index of the element.

[Visual Basic]
Overloads Public Overridable Function BinarySearch( _
   ByVal value As Object _
) As Integer
[C#]
public virtual int BinarySearch(
 object value
);
[C++]
public: virtual int BinarySearch(
 Object* value
);
[JScript]
public function BinarySearch(
   value : Object
) : int;

Parameters

value
The Object to locate. The value can be a null reference (Nothing in Visual Basic).

Return Value

The zero-based index of value in the sorted ArrayList, if value is found; otherwise, a negative number, which is the bitwise complement of the index of the next element that is larger than value or, if there is no larger element, the bitwise complement of Count.

Exceptions

Exception Type Condition
ArgumentException Neither value nor the elements of ArrayList implement the IComparable interface.
InvalidOperationException value is not of the same type as the elements of the ArrayList.

Remarks

The value parameter and each element of the ArrayList must implement the IComparable interface, which is used for comparisons. If the ArrayList is not already sorted according to the IComparable implementation, the result might be incorrect.

Comparing a null reference (Nothing in Visual Basic) with any type is allowed and does not generate an exception when using IComparable. When sorting, a null reference (Nothing) is considered to be less than any other object.

If the ArrayList contains more than one element with the same value, the method returns only one of the occurrences, and it might return any one of the occurrences, not necessarily the first one.

If the ArrayList does not contain the specified value, the method returns a negative integer. You can apply the bitwise complement operation (~) to this negative integer to get the index of the first element that is larger than the search value. When inserting the value into the ArrayList, this index should be used as the insertion point to maintain the sort order.

This method is an O(log2 n) operation, where n is the number of elements in the range.

Example

The following example shows how to use BinarySearch to locate a specific object in the ArrayList.

[Visual Basic] 
Imports System
Imports System.Collections
Imports Microsoft.VisualBasic

Public Class SamplesArrayList    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new ArrayList.
        Dim myAL As New ArrayList()
        Dim i As Integer
        For i = 0 To 4
            myAL.Add(i * 2)
        Next i 
        ' Displays the ArrayList.
        Console.WriteLine("The Int32 ArrayList contains the following:")
        PrintValues(myAL)
        
        ' Locates a specific object that does not exist in the ArrayList.
        Dim myObjectOdd As Object = 3
        FindMyObject(myAL, myObjectOdd)
        
        ' Locates an object that exists in the ArrayList.
        Dim myObjectEven As Object = 6
        FindMyObject(myAL, myObjectEven)
    End Sub    
    
    Public Shared Sub FindMyObject(myList As ArrayList, myObject As Object)
        Dim myIndex As Integer = myList.BinarySearch(myObject)
        If myIndex < 0 Then
            Console.WriteLine("The object to search for ({0}) is not found. " _
               + "The next larger object is at index {1}.", myObject, _
               Not myIndex)
        Else
            Console.WriteLine("The object to search for ({0}) is at index " _
               + "{1}.", myObject, myIndex)
        End If
    End Sub
     
    Public Shared Sub PrintValues(myList As IEnumerable)
        Dim myEnumerator As System.Collections.IEnumerator = _
           myList.GetEnumerator()
        While myEnumerator.MoveNext()
            Console.Write(ControlChars.Tab + "{0}", myEnumerator.Current)
        End While
        Console.WriteLine()
    End Sub
    
End Class

' This code produces the following output.
' 
' The Int32 ArrayList contains the following:
'     0    2    4    6    8
' The object to search for (3) is not found. The next larger object is at index 2.
' The object to search for (6) is at index 3. 

[C#] 
using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList.
      ArrayList myAL = new ArrayList();
      for ( int i = 0; i <= 4; i++ )
         myAL.Add( i*2 );

      // Displays the ArrayList.
      Console.WriteLine( "The Int32 ArrayList contains the following:" );
      PrintValues( myAL );

      // Locates a specific object that does not exist in the ArrayList.
      Object myObjectOdd = 3;
      FindMyObject( myAL, myObjectOdd );

      // Locates an object that exists in the ArrayList.
      Object myObjectEven = 6;
      FindMyObject( myAL, myObjectEven );
   }

   public static void FindMyObject( ArrayList myList, Object myObject )  {
      int myIndex=myList.BinarySearch( myObject );
      if ( myIndex < 0 )
         Console.WriteLine( "The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, ~myIndex );
      else
         Console.WriteLine( "The object to search for ({0}) is at index {1}.", myObject, myIndex );
   }

   public static void PrintValues( IEnumerable myList )  {
      System.Collections.IEnumerator myEnumerator = myList.GetEnumerator();
      while ( myEnumerator.MoveNext() )
         Console.Write( "\t{0}", myEnumerator.Current );
      Console.WriteLine();
   }
}
/* 
This code produces the following output.

The Int32 ArrayList contains the following:
    0    2    4    6    8
The object to search for (3) is not found. The next larger object is at index 2.
The object to search for (6) is at index 3.
*/ 

[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::Collections;

void FindMyObject( ArrayList* myList, Object* myObject );
void PrintValues( IEnumerable* myList );
 
void main() {
 
    // Creates and initializes a new ArrayList instance.
    ArrayList* myAL = new ArrayList();
    for ( int i = 0; i <= 4; i++ )
        myAL->Add( __box(i*2) );
 
    // Displays the ArrayList.
    Console::WriteLine( "The Int32 ArrayList contains the following:" );
    PrintValues( myAL );
 
    // Locates a specific object that does not exist in the ArrayList.
    Object* myObjectOdd = __box(3);
    FindMyObject( myAL, myObjectOdd );
 
    // Locates an object that exists in the ArrayList.
    Object* myObjectEven = __box(6);
    FindMyObject( myAL, myObjectEven );
}
 
void FindMyObject( ArrayList* myList, Object* myObject ) {
    int myIndex = myList->BinarySearch( myObject );
    if ( myIndex < 0 )
        Console::WriteLine( "The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, __box(~myIndex) );
    else
        Console::WriteLine( "The object to search for ({0}) is at index {1}.", myObject, __box(myIndex) );
}
 
void PrintValues( IEnumerable* myList ) {
    System::Collections::IEnumerator* myEnumerator = myList->GetEnumerator();
    while ( myEnumerator->MoveNext() )
        Console::Write( "\t{0}", myEnumerator->Current );
    Console::WriteLine();
}

 /* 
 This code produces the following output.
 
 The Int32 ArrayList contains the following:
     0    2    4    6    8
 The object to search for (3) is not found. The next larger object is at index 2.
 The object to search for (6) is at index 3.
 */ 

[JScript] 
import System;
import System.Collections;


// Creates and initializes a new ArrayList.
var myAL : ArrayList = new ArrayList();
for ( var i : int = 0; i <= 4; i++ )
  myAL.Add( int(i*2 ));

// Displays the ArrayList.
Console.WriteLine( "The Int32 ArrayList contains the following:" );
PrintValues( myAL );

// Locates a specific object that does not exist in the ArrayList.
var myObjectOdd = 3;
FindMyObject( myAL, myObjectOdd );

// Locates an object that exists in the ArrayList.
var  myObjectEven = 6;
FindMyObject( myAL, myObjectEven );


function FindMyObject( myList : ArrayList, myObject )  {
   var myIndex : int = myList.BinarySearch( myObject );
   if ( myIndex < 0 )
      Console.WriteLine( "The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, ~myIndex );
   else
      Console.WriteLine( "The object to search for ({0}) is at index {1}.", myObject, myIndex );
}

function PrintValues( myList : IEnumerable)  {
   var myEnumerator : System.Collections.IEnumerator = myList.GetEnumerator();
   while ( myEnumerator.MoveNext() )
      Console.Write( "\t{0}", myEnumerator.Current );
   Console.WriteLine();
}
 /* 
 This code produces the following output.
 
 The Int32 ArrayList contains the following:
     0    2    4    6    8
 The object to search for (3) is not found. The next larger object is at index 2.
 The object to search for (6) is at index 3.
 */ 

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, Common Language Infrastructure (CLI) Standard

See Also

ArrayList Class | ArrayList Members | System.Collections Namespace | ArrayList.BinarySearch Overload List | Performing Culture-Insensitive String Operations in Collections

Show: