Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.
Traducción
Inglés

Método ArrayList.BinarySearch (Object, IComparer)

 

Publicado: octubre de 2016

Busca la ArrayList completa ordenada para un elemento usando el comparador especificado y devuelve el índice de base cero del elemento.

Espacio de nombres:   System.Collections
Ensamblado:  mscorlib (en mscorlib.dll)

public virtual int BinarySearch(
	object value,
	IComparer comparer
)

Parámetros

value
Type: System.Object

Clase Object que se va a localizar. El valor puede ser null.

comparer
Type: System.Collections.IComparer

Implementación de IComparer que se va a usar al comparar elementos.

O bien

null para utilizar el comparador predeterminado, que es la implementación de IComparable de cada elemento.

Valor devuelto

Type: System.Int32

Í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.

Exception Condition
ArgumentException

comparer es null y ni value ni los elementos de ArrayList implementan la interfaz de IComparable

InvalidOperationException

comparer es null y value no es del mismo tipo que los elementos de ArrayList.

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

If comparer is provided, the elements of the T:System.Collections.ArrayList are compared to the specified value using the specified T:System.Collections.IComparer implementation. The elements of the T:System.Collections.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 T:System.IComparable implementation provided by the element itself or by the specified value. The elements of the T:System.Collections.ArrayList must already be sorted in increasing value according to the sort order defined by the T:System.IComparable implementation; otherwise, the result might be incorrect.

Comparing null with any type is allowed and does not generate an exception when using T:System.IComparable. When sorting, null is considered to be less than any other object.

If the T:System.Collections.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 T:System.Collections.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 T:System.Collections.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 P:System.Collections.ArrayList.Count.

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

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
//

Plataforma universal de Windows
Disponible desde 10
.NET Framework
Disponible desde 1.1
Volver al principio
Mostrar: