Szerkesztés

Megosztás a következőn keresztül:


ArrayList.BinarySearch Method

Definition

Uses a binary search algorithm to locate a specific element in the sorted ArrayList or a portion of it.

Overloads

BinarySearch(Object)

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

BinarySearch(Object, IComparer)

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

BinarySearch(Int32, Int32, Object, IComparer)

Searches a range of elements in the sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.

BinarySearch(Object)

Source:
ArrayList.cs
Source:
ArrayList.cs
Source:
ArrayList.cs

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

public:
 virtual int BinarySearch(System::Object ^ value);
public virtual int BinarySearch (object value);
public virtual int BinarySearch (object? value);
abstract member BinarySearch : obj -> int
override this.BinarySearch : obj -> int
Public Overridable Function BinarySearch (value As Object) As Integer

Parameters

value
Object

The Object to locate. The value can be null.

Returns

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

Neither value nor the elements of ArrayList implement the IComparable interface.

value is not of the same type as the elements of the ArrayList.

Examples

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

using namespace System;
using namespace System::Collections;
void FindMyObject( ArrayList^ myList, Object^ myObject );
void PrintValues( IEnumerable^ myList );
int main()
{
   
   // Creates and initializes a new ArrayList. BinarySearch requires
   // a sorted ArrayList.
   ArrayList^ myAL = gcnew 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 );
}

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 );
}

void PrintValues( IEnumerable^ myList )
{
   IEnumerator^ myEnum = myList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Object^ obj = safe_cast<Object^>(myEnum->Current);
      Console::Write( "   {0}", obj );
   }

   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.
 */
using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

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

      // Displays the ArrayList.
      Console.WriteLine( "The int 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 )  {
      foreach ( Object obj in myList )
         Console.Write( "   {0}", obj );
      Console.WriteLine();
   }
}
/*
This code produces the following output.

The int 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.
*/
Imports System.Collections

Public Class SamplesArrayList    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new ArrayList. BinarySearch requires
        ' a sorted 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 obj As [Object]
        For Each obj In  myList
            Console.Write("   {0}", obj)
        Next obj
        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.

Remarks

The value parameter and each element of the ArrayList must implement the IComparable interface, which is used for comparisons. The elements of the ArrayList must already be sorted in increasing value according to the sort order defined by the IComparable implementation; otherwise, the result might be incorrect.

Comparing null with any type is allowed and does not generate an exception when using IComparable. When sorting, null 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(log n) operation, where n is Count.

See also

Applies to

BinarySearch(Object, IComparer)

Source:
ArrayList.cs
Source:
ArrayList.cs
Source:
ArrayList.cs

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

public:
 virtual int BinarySearch(System::Object ^ value, System::Collections::IComparer ^ comparer);
public virtual int BinarySearch (object value, System.Collections.IComparer comparer);
public virtual int BinarySearch (object? value, System.Collections.IComparer? comparer);
abstract member BinarySearch : obj * System.Collections.IComparer -> int
override this.BinarySearch : obj * System.Collections.IComparer -> int
Public Overridable Function BinarySearch (value As Object, comparer As IComparer) As Integer

Parameters

value
Object

The Object to locate. The value can be null.

comparer
IComparer

The IComparer implementation to use when comparing elements.

-or-

null to use the default comparer that is the IComparable implementation of each element.

Returns

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

comparer is null and neither value nor the elements of ArrayList implement the IComparable interface.

comparer is null and value is not of the same type as the elements of the ArrayList.

Examples

The following example creates an ArrayList of colored animals. The provided IComparer performs the string comparison for the binary search. The results of both an iterative search and a binary search are displayed.

using namespace System;
using namespace System::Collections;

public ref class SimpleStringComparer : public IComparer
{
    virtual int Compare(Object^ x, Object^ y) sealed = IComparer::Compare
    {
        String^ cmpstr = (String^)x;
        return cmpstr->CompareTo((String^)y);
    }
};

public ref class MyArrayList : public ArrayList
{
public:
    static void Main()
    {
        // Creates and initializes a new ArrayList.
        MyArrayList^ coloredAnimals = gcnew MyArrayList();

        coloredAnimals->Add("White Tiger");
        coloredAnimals->Add("Pink Bunny");
        coloredAnimals->Add("Red Dragon");
        coloredAnimals->Add("Green Frog");
        coloredAnimals->Add("Blue Whale");
        coloredAnimals->Add("Black Cat");
        coloredAnimals->Add("Yellow Lion");

        // BinarySearch requires a sorted ArrayList.
        coloredAnimals->Sort();

        // Compare results of an iterative search with a binary search
        int index = coloredAnimals->IterativeSearch("White Tiger");
        Console::WriteLine("Iterative search, item found at index: {0}", index);

        index = coloredAnimals->BinarySearch("White Tiger", gcnew SimpleStringComparer());
        Console::WriteLine("Binary search, item found at index:    {0}", index);
    }

    int IterativeSearch(Object^ finditem)
    {
        int index = -1;

        for (int i = 0; i < this->Count; i++)
        {
            if (finditem->Equals(this[i]))
            {
                index = i;
                break;
            }
        }
        return index;
    }
};

int main()
{
    MyArrayList::Main();
}
//
// This code produces the following output.
//
// Iterative search, item found at index: 5
// Binary search, item found at index:    5
//
using System;
using System.Collections;

public class SimpleStringComparer : IComparer
{
    int IComparer.Compare(object x, object y)
    {
        string cmpstr = (string)x;
        return cmpstr.CompareTo((string)y);
    }
}

public class MyArrayList : ArrayList
{
    public static void Main()
    {
        // Creates and initializes a new ArrayList.
        MyArrayList coloredAnimals = new MyArrayList();

        coloredAnimals.Add("White Tiger");
        coloredAnimals.Add("Pink Bunny");
        coloredAnimals.Add("Red Dragon");
        coloredAnimals.Add("Green Frog");
        coloredAnimals.Add("Blue Whale");
        coloredAnimals.Add("Black Cat");
        coloredAnimals.Add("Yellow Lion");

        // BinarySearch requires a sorted ArrayList.
        coloredAnimals.Sort();

        // Compare results of an iterative search with a binary search
        int index = coloredAnimals.IterativeSearch("White Tiger");
        Console.WriteLine("Iterative search, item found at index: {0}", index);

        index = coloredAnimals.BinarySearch("White Tiger", new SimpleStringComparer());
        Console.WriteLine("Binary search, item found at index:    {0}", index);
    }

    public int IterativeSearch(object finditem)
    {
        int index = -1;

        for (int i = 0; i < this.Count; i++)
        {
            if (finditem.Equals(this[i]))
            {
                index = i;
                break;
            }
        }
        return index;
    }
}
//
// This code produces the following output.
//
// Iterative search, item found at index: 5
// Binary search, item found at index:    5
//
Imports System.Collections

Public Class SimpleStringComparer
    Implements IComparer

    Function Compare(x As Object, y As Object) As Integer Implements IComparer.Compare
          Dim cmpstr As String = CType(x, String)
          Return cmpstr.CompareTo(CType(y, String))
    End Function
End Class

Public Class MyArrayList
    Inherits ArrayList

    Public Shared Sub Main()
        ' Creates and initializes a new ArrayList.
        Dim coloredAnimals As New MyArrayList()

        coloredAnimals.Add("White Tiger")
        coloredAnimals.Add("Pink Bunny")
        coloredAnimals.Add("Red Dragon")
        coloredAnimals.Add("Green Frog")
        coloredAnimals.Add("Blue Whale")
        coloredAnimals.Add("Black Cat")
        coloredAnimals.Add("Yellow Lion")

        ' BinarySearch requires a sorted ArrayList.
        coloredAnimals.Sort()

        ' Compare results of an iterative search with a binary search
        Dim index As Integer = coloredAnimals.IterativeSearch("White Tiger")
        Console.WriteLine("Iterative search, item found at index: {0}", index)

        index = coloredAnimals.BinarySearch("White Tiger", New SimpleStringComparer())
        Console.WriteLine("Binary search, item found at index:    {0}", index)
    End Sub

    Public Function IterativeSearch(finditem As Object) As Integer
        Dim index As Integer = -1

        For i As Integer = 0 To MyClass.Count - 1
            If finditem.Equals(MyClass.Item(i))
                index = i
                Exit For
            End If
        Next i
        Return index
    End Function
End Class
'
' This code produces the following output.
'
' Iterative search, item found at index: 5
' Binary search, item found at index:    5
'

Remarks

The comparer customizes how the elements are compared. For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.

If comparer is provided, the elements of the ArrayList are compared to the specified value using the specified IComparer implementation. The elements of the ArrayList must already be sorted in increasing value according to the sort order defined by comparer; otherwise, the result might be incorrect.

If comparer is null, the comparison is done using the IComparable implementation provided by the element itself or by the specified value. The elements of the ArrayList must already be sorted in increasing value according to the sort order defined by the IComparable implementation; otherwise, the result might be incorrect.

Comparing null with any type is allowed and does not generate an exception when using IComparable. When sorting, null 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(log n) operation, where n is Count.

See also

Applies to

BinarySearch(Int32, Int32, Object, IComparer)

Source:
ArrayList.cs
Source:
ArrayList.cs
Source:
ArrayList.cs

Searches a range of elements in the sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.

public:
 virtual int BinarySearch(int index, int count, System::Object ^ value, System::Collections::IComparer ^ comparer);
public virtual int BinarySearch (int index, int count, object value, System.Collections.IComparer comparer);
public virtual int BinarySearch (int index, int count, object? value, System.Collections.IComparer? comparer);
abstract member BinarySearch : int * int * obj * System.Collections.IComparer -> int
override this.BinarySearch : int * int * obj * System.Collections.IComparer -> int
Public Overridable Function BinarySearch (index As Integer, count As Integer, value As Object, comparer As IComparer) As Integer

Parameters

index
Int32

The zero-based starting index of the range to search.

count
Int32

The length of the range to search.

value
Object

The Object to locate. The value can be null.

comparer
IComparer

The IComparer implementation to use when comparing elements.

-or-

null to use the default comparer that is the IComparable implementation of each element.

Returns

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

index and count do not denote a valid range in the ArrayList.

-or-

comparer is null and neither value nor the elements of ArrayList implement the IComparable interface.

comparer is null and value is not of the same type as the elements of the ArrayList.

index is less than zero.

-or-

count is less than zero.

Remarks

The comparer customizes how the elements are compared. For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.

If comparer is provided, the elements of the ArrayList are compared to the specified value using the specified IComparer implementation. The elements of the ArrayList must already be sorted in increasing value according to the sort order defined by comparer; otherwise, the result might be incorrect.

If comparer is null, the comparison is done using the IComparable implementation provided by the element itself or by the specified value. The elements of the ArrayList must already be sorted in increasing value according to the sort order defined by the IComparable implementation; otherwise, the result might be incorrect.

Comparing null with any type is allowed and does not generate an exception when using IComparable. When sorting, null 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(log n) operation, where n is count.

See also

Applies to