ArrayList.BinarySearch ArrayList.BinarySearch ArrayList.BinarySearch ArrayList.BinarySearch Method

Definición

Utiliza un algoritmo de búsqueda binaria para localizar un elemento concreto en la ArrayList ordenada o en una parte de ella.Uses a binary search algorithm to locate a specific element in the sorted ArrayList or a portion of it.

Sobrecargas

BinarySearch(Object) BinarySearch(Object) BinarySearch(Object) BinarySearch(Object)

Busca la ArrayList completa ordenada para un elemento usando el comparador predeterminado y devuelve el índice de base cero del elemento.Searches the entire sorted ArrayList for an element using the default comparer and returns the zero-based index of the element.

BinarySearch(Object, IComparer) BinarySearch(Object, IComparer) BinarySearch(Object, IComparer) BinarySearch(Object, IComparer)

Busca la ArrayList completa ordenada para un elemento usando el comparador especificado y devuelve el índice de base cero del elemento.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) BinarySearch(Int32, Int32, Object, IComparer) BinarySearch(Int32, Int32, Object, IComparer) BinarySearch(Int32, Int32, Object, IComparer)

Busca un elemento en un intervalo de elementos del objeto ArrayList ordenado usando el comparador especificado y devuelve el índice de base cero del elemento.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) BinarySearch(Object) BinarySearch(Object) BinarySearch(Object)

Busca la ArrayList completa ordenada para un elemento usando el comparador predeterminado y devuelve el índice de base cero del elemento.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);
abstract member BinarySearch : obj -> int
override this.BinarySearch : obj -> int
Public Overridable Function BinarySearch (value As Object) As Integer

Parámetros

value
Object Object Object Object

Clase Object que se va a localizar.The Object to locate. El valor puede ser null.The value can be null.

Devoluciones

Índice de base cero de value en la ArrayList ordenada si se encuentra value; en caso contrario, número negativo, que es el complemento bit a bit del índice del siguiente elemento mayor que value o, si no hay ningún elemento mayor, el complemento bit a bit de la propiedad Count.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.

Excepciones

Ni value ni los elementos de ArrayList implementan la interfaz IComparable.Neither value nor the elements of ArrayList implement the IComparable interface.

value no es del mismo tipo que los elementos de ArrayList.value is not of the same type as the elements of the ArrayList.

Ejemplos

En el ejemplo de código siguiente se muestra BinarySearch cómo usar para buscar un objeto específico en. ArrayListThe 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 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 )  {
      foreach ( Object obj in myList )
         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.
*/ 
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. 

Comentarios

El value parámetro y cada elemento ArrayList de deben implementar la interfaz IComparable , que se utiliza para las comparaciones.The value parameter and each element of the ArrayList must implement the IComparable interface, which is used for comparisons. Los elementos de ArrayList ya deben estar ordenados en el valor creciente según el criterio de ordenación definido por IComparable la implementación; de lo contrario, el resultado podría ser incorrecto.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.

Se permite comparar IComparable concualquiertipoynogeneraunaexcepciónnull cuando se usa.Comparing null with any type is allowed and does not generate an exception when using IComparable. Al ordenar, null se considera que es menor que cualquier otro objeto.When sorting, null is considered to be less than any other object.

ArrayList Si contiene más de un elemento con el mismo valor, el método solo devuelve una de las repeticiones y puede devolver cualquiera de las apariciones, no necesariamente la primera.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.

ArrayList Si no contiene el valor especificado, el método devuelve un entero negativo.If the ArrayList does not contain the specified value, the method returns a negative integer. Puede aplicar la operación de complemento bit a bit (~) a este entero negativo para obtener el índice del primer elemento que sea mayor que el valor de búsqueda.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. Al insertar el valor en ArrayList, este índice se debe utilizar como punto de inserción para mantener el criterio de ordenación.When inserting the value into the ArrayList, this index should be used as the insertion point to maintain the sort order.

Este método es una operación O ( nlog), donde n es Count.This method is an O(log n) operation, where n is Count.

Consulte también:

BinarySearch(Object, IComparer) BinarySearch(Object, IComparer) BinarySearch(Object, IComparer) BinarySearch(Object, IComparer)

Busca la ArrayList completa ordenada para un elemento usando el comparador especificado y devuelve el índice de base cero del elemento.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);
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

Parámetros

value
Object Object Object Object

Clase Object que se va a localizar.The Object to locate. El valor puede ser null.The value can be null.

comparer
IComparer IComparer IComparer IComparer

Implementación de IComparer que se va a usar al comparar elementos.The IComparer implementation to use when comparing elements.

o bien-or- null para utilizar el comparador predeterminado, que es la implementación de IComparable de cada elemento.null to use the default comparer that is the IComparable implementation of each element.

Devoluciones

Índice de base cero de value en la ArrayList ordenada si se encuentra value; en caso contrario, número negativo, que es el complemento bit a bit del índice del siguiente elemento mayor que value o, si no hay ningún elemento mayor, el complemento bit a bit de la propiedad Count.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.

Excepciones

comparer es null y ni value ni los elementos de ArrayList implementan la interfaz de IComparablecomparer is null and neither value nor the elements of ArrayList implement the IComparable interface.

comparer es null y value no es del mismo tipo que los elementos de ArrayList.comparer is null and value is not of the same type as the elements of the ArrayList.

Ejemplos

En el ejemplo siguiente se ArrayList crea una de animales en color.The following example creates an ArrayList of colored animals. El proporcionado IComparer realiza la comparación de cadenas para la búsqueda binaria.The provided IComparer performs the string comparison for the binary search. Se muestran los resultados de una búsqueda iterativa y una búsqueda binaria.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
'

Comentarios

El comparador Personaliza el modo en que se comparan los elementos.The comparer customizes how the elements are compared. Por ejemplo, puede usar una CaseInsensitiveComparer instancia como comparador para realizar búsquedas de cadenas que no distinguen entre mayúsculas y minúsculas.For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.

Si comparer se proporciona, los elementos ArrayList de se comparan con el valor especificado mediante la IComparer implementación de especificada.If comparer is provided, the elements of the ArrayList are compared to the specified value using the specified IComparer implementation. Los elementos de ArrayList ya deben estar ordenados en el valor creciente según el criterio de ordenación definido comparerpor; de lo contrario, el resultado podría ser incorrecto.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.

Si comparer IComparable es null, la comparación se realiza mediante la implementación proporcionada por el propio elemento o por el valor especificado.If comparer is null, the comparison is done using the IComparable implementation provided by the element itself or by the specified value. Los elementos de ArrayList ya deben estar ordenados en el valor creciente según el criterio de ordenación definido por IComparable la implementación; de lo contrario, el resultado podría ser incorrecto.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.

Se permite comparar IComparable concualquiertipoynogeneraunaexcepciónnull cuando se usa.Comparing null with any type is allowed and does not generate an exception when using IComparable. Al ordenar, null se considera que es menor que cualquier otro objeto.When sorting, null is considered to be less than any other object.

ArrayList Si contiene más de un elemento con el mismo valor, el método solo devuelve una de las repeticiones y puede devolver cualquiera de las apariciones, no necesariamente la primera.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.

ArrayList Si no contiene el valor especificado, el método devuelve un entero negativo.If the ArrayList does not contain the specified value, the method returns a negative integer. Puede aplicar la operación de complemento bit a bit (~) a este entero negativo para obtener el índice del primer elemento que sea mayor que el valor de búsqueda.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. Al insertar el valor en ArrayList, este índice se debe utilizar como punto de inserción para mantener el criterio de ordenación.When inserting the value into the ArrayList, this index should be used as the insertion point to maintain the sort order.

Este método es una operación O ( nlog), donde n es Count.This method is an O(log n) operation, where n is Count.

Consulte también:

BinarySearch(Int32, Int32, Object, IComparer) BinarySearch(Int32, Int32, Object, IComparer) BinarySearch(Int32, Int32, Object, IComparer) BinarySearch(Int32, Int32, Object, IComparer)

Busca un elemento en un intervalo de elementos del objeto ArrayList ordenado usando el comparador especificado y devuelve el índice de base cero del elemento.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);
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

Parámetros

index
Int32 Int32 Int32 Int32

Índice inicial de base cero del intervalo que se va a buscar.The zero-based starting index of the range to search.

count
Int32 Int32 Int32 Int32

Longitud del intervalo en el que se va a buscar.The length of the range to search.

value
Object Object Object Object

Clase Object que se va a localizar.The Object to locate. El valor puede ser null.The value can be null.

comparer
IComparer IComparer IComparer IComparer

Implementación de IComparer que se va a usar al comparar elementos.The IComparer implementation to use when comparing elements.

o bien-or- null para utilizar el comparador predeterminado, que es la implementación de IComparable de cada elemento.null to use the default comparer that is the IComparable implementation of each element.

Devoluciones

Índice de base cero de value en la ArrayList ordenada si se encuentra value; en caso contrario, número negativo, que es el complemento bit a bit del índice del siguiente elemento mayor que value o, si no hay ningún elemento mayor, el complemento bit a bit de la propiedad Count.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.

Excepciones

index y count no denotan un intervalo válido en ArrayList.index and count do not denote a valid range in the ArrayList.

O bien-or- comparer es null y ni value ni los elementos de ArrayList implementan la interfaz de IComparablecomparer is null and neither value nor the elements of ArrayList implement the IComparable interface.

comparer es null y value no es del mismo tipo que los elementos de ArrayList.comparer is null and value is not of the same type as the elements of the ArrayList.

index es menor que cero.index is less than zero.

O bien-or- count es menor que cero.count is less than zero.

Comentarios

El comparador Personaliza el modo en que se comparan los elementos.The comparer customizes how the elements are compared. Por ejemplo, puede usar una CaseInsensitiveComparer instancia como comparador para realizar búsquedas de cadenas que no distinguen entre mayúsculas y minúsculas.For example, you can use a CaseInsensitiveComparer instance as the comparer to perform case-insensitive string searches.

Si comparer se proporciona, los elementos ArrayList de se comparan con el valor especificado mediante la IComparer implementación de especificada.If comparer is provided, the elements of the ArrayList are compared to the specified value using the specified IComparer implementation. Los elementos de ArrayList ya deben estar ordenados en el valor creciente según el criterio de ordenación definido comparerpor; de lo contrario, el resultado podría ser incorrecto.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.

Si comparer IComparable es null, la comparación se realiza mediante la implementación proporcionada por el propio elemento o por el valor especificado.If comparer is null, the comparison is done using the IComparable implementation provided by the element itself or by the specified value. Los elementos de ArrayList ya deben estar ordenados en el valor creciente según el criterio de ordenación definido por IComparable la implementación; de lo contrario, el resultado podría ser incorrecto.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.

Se permite comparar IComparable concualquiertipoynogeneraunaexcepciónnull cuando se usa.Comparing null with any type is allowed and does not generate an exception when using IComparable. Al ordenar, null se considera que es menor que cualquier otro objeto.When sorting, null is considered to be less than any other object.

ArrayList Si contiene más de un elemento con el mismo valor, el método solo devuelve una de las repeticiones y puede devolver cualquiera de las apariciones, no necesariamente la primera.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.

ArrayList Si no contiene el valor especificado, el método devuelve un entero negativo.If the ArrayList does not contain the specified value, the method returns a negative integer. Puede aplicar la operación de complemento bit a bit (~) a este entero negativo para obtener el índice del primer elemento que sea mayor que el valor de búsqueda.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. Al insertar el valor en ArrayList, este índice se debe utilizar como punto de inserción para mantener el criterio de ordenación.When inserting the value into the ArrayList, this index should be used as the insertion point to maintain the sort order.

Este método es una operación O ( nlog), donde n es count.This method is an O(log n) operation, where n is count.

Consulte también:

Se aplica a