ArrayList.BinarySearch Méthode

Définition

Utilise un algorithme de recherche binaire pour trouver un élément spécifique dans le ArrayList trié ou une partie de celui-ci.

Surcharges

BinarySearch(Object)

Recherche un élément utilisant le comparateur par défaut dans le ArrayList entièrement trié et retourne l'index de base zéro de l'élément.

BinarySearch(Object, IComparer)

Recherche un élément utilisant le comparateur spécifié dans le ArrayList entièrement trié et retourne l'index de base zéro de l'élément.

BinarySearch(Int32, Int32, Object, IComparer)

Recherche un élément utilisant le comparateur spécifié dans une plage d'éléments du ArrayList trié et retourne l'index de base zéro de l'élément.

BinarySearch(Object)

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

Recherche un élément utilisant le comparateur par défaut dans le ArrayList entièrement trié et retourne l'index de base zéro de l'élément.

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

Paramètres

value
Object

Object à rechercher. La valeur peut être null.

Retours

Index de base zéro de value dans le ArrayList trié, si value existe ; sinon, un nombre négatif qui est le complément de bits de l’index de l’élément suivant supérieur à value ou, s’il n’existe aucun élément supérieur, le complément de bits de Count.

Exceptions

Ni value ni les éléments d’ArrayList n’implémentent l’interface IComparable.

value n’est pas du même type que les éléments de l’ArrayList.

Exemples

L’exemple de code suivant montre comment utiliser BinarySearch pour localiser un objet spécifique dans le 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.

Remarques

Le value paramètre et chaque élément de doivent ArrayList implémenter l’interface IComparable , qui est utilisée pour les comparaisons. Les éléments de doivent ArrayList déjà être triés en valeur croissante selon l’ordre de tri défini par l’implémentation IComparable ; sinon, le résultat peut être incorrect.

La comparaison null avec n’importe quel type est autorisée et ne génère pas d’exception lors de l’utilisation de IComparable. Lors du tri, null est considéré comme inférieur à tout autre objet.

Si contient ArrayList plusieurs éléments ayant la même valeur, la méthode ne retourne qu’une seule des occurrences, et elle peut retourner l’une des occurrences, pas nécessairement la première.

Si le ArrayList ne contient pas la valeur spécifiée, la méthode retourne un entier négatif. Vous pouvez appliquer l’opération de complément au niveau du bit (~) à cet entier négatif pour obtenir l’index du premier élément supérieur à la valeur de recherche. Lors de l’insertion de la valeur dans , ArrayListcet index doit être utilisé comme point d’insertion pour conserver l’ordre de tri.

Cette méthode est une O(log n) opération, où n est Count.

Voir aussi

S’applique à

BinarySearch(Object, IComparer)

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

Recherche un élément utilisant le comparateur spécifié dans le ArrayList entièrement trié et retourne l'index de base zéro de l'élément.

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

Paramètres

value
Object

Object à rechercher. La valeur peut être null.

comparer
IComparer

Implémentation de IComparer à utiliser pendant la comparaison d’éléments.

- ou -

null pour utiliser le comparateur par défaut qui correspond à l’implémentation IComparable de chaque élément.

Retours

Index de base zéro de value dans le ArrayList trié, si value existe ; sinon, un nombre négatif qui est le complément de bits de l’index de l’élément suivant supérieur à value ou, s’il n’existe aucun élément supérieur, le complément de bits de Count.

Exceptions

comparer est null, et ni value ni les éléments de ArrayList n’implémentent l’interface IComparable.

comparer est null, et value n’est pas du même type que les éléments de ArrayList.

Exemples

L’exemple suivant crée un ArrayList d’animaux colorés. Le fourni IComparer effectue la comparaison de chaînes pour la recherche binaire. Les résultats d’une recherche itérative et d’une recherche binaire s’affichent.

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
'

Remarques

Le comparateur personnalise la façon dont les éléments sont comparés. Par exemple, vous pouvez utiliser un CaseInsensitiveComparer instance comme comparateur pour effectuer des recherches de chaînes qui ne respectent pas la casse.

Si comparer est fourni, les éléments de sont ArrayList comparés à la valeur spécifiée à l’aide de l’implémentation spécifiée IComparer . Les éléments du ArrayList doivent déjà être triés en valeur croissante selon l’ordre de tri défini par comparer; sinon, le résultat peut être incorrect.

Si comparer a nullla valeur , la comparaison est effectuée à l’aide de l’implémentation IComparable fournie par l’élément lui-même ou par la valeur spécifiée. Les éléments de doivent ArrayList déjà être triés en valeur croissante selon l’ordre de tri défini par l’implémentation IComparable ; sinon, le résultat peut être incorrect.

La comparaison null avec n’importe quel type est autorisée et ne génère pas d’exception lors de l’utilisation de IComparable. Lors du tri, null est considéré comme inférieur à tout autre objet.

Si contient ArrayList plusieurs éléments ayant la même valeur, la méthode ne retourne qu’une seule des occurrences, et elle peut retourner l’une des occurrences, pas nécessairement la première.

Si le ArrayList ne contient pas la valeur spécifiée, la méthode retourne un entier négatif. Vous pouvez appliquer l’opération de complément au niveau du bit (~) à cet entier négatif pour obtenir l’index du premier élément supérieur à la valeur de recherche. Lors de l’insertion de la valeur dans , ArrayListcet index doit être utilisé comme point d’insertion pour conserver l’ordre de tri.

Cette méthode est une O(log n) opération, où n est Count.

Voir aussi

S’applique à

BinarySearch(Int32, Int32, Object, IComparer)

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

Recherche un élément utilisant le comparateur spécifié dans une plage d'éléments du ArrayList trié et retourne l'index de base zéro de l'élément.

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

Paramètres

index
Int32

Index de début de base zéro de la plage dans laquelle effectuer la recherche.

count
Int32

Longueur de la plage dans laquelle effectuer la recherche.

value
Object

Object à rechercher. La valeur peut être null.

comparer
IComparer

Implémentation de IComparer à utiliser pendant la comparaison d’éléments.

- ou -

null pour utiliser le comparateur par défaut qui correspond à l’implémentation IComparable de chaque élément.

Retours

Index de base zéro de value dans le ArrayList trié, si value existe ; sinon, un nombre négatif qui est le complément de bits de l’index de l’élément suivant supérieur à value ou, s’il n’existe aucun élément supérieur, le complément de bits de Count.

Exceptions

index et count ne désignent pas une plage valide dans ArrayList.

- ou -

comparer est null, et ni value ni les éléments de ArrayList n’implémentent l’interface IComparable.

comparer est null, et value n’est pas du même type que les éléments de ArrayList.

index est inférieur à zéro.

- ou -

count est inférieur à zéro.

Remarques

Le comparateur personnalise la façon dont les éléments sont comparés. Par exemple, vous pouvez utiliser un CaseInsensitiveComparer instance comme comparateur pour effectuer des recherches de chaînes qui ne respectent pas la casse.

Si comparer est fourni, les éléments de sont ArrayList comparés à la valeur spécifiée à l’aide de l’implémentation spécifiée IComparer . Les éléments du ArrayList doivent déjà être triés en valeur croissante selon l’ordre de tri défini par comparer; sinon, le résultat peut être incorrect.

Si comparer a nullla valeur , la comparaison est effectuée à l’aide de l’implémentation IComparable fournie par l’élément lui-même ou par la valeur spécifiée. Les éléments de doivent ArrayList déjà être triés en valeur croissante selon l’ordre de tri défini par l’implémentation IComparable ; sinon, le résultat peut être incorrect.

La comparaison null avec n’importe quel type est autorisée et ne génère pas d’exception lors de l’utilisation de IComparable. Lors du tri, null est considéré comme inférieur à tout autre objet.

Si contient ArrayList plusieurs éléments ayant la même valeur, la méthode ne retourne qu’une seule des occurrences, et elle peut retourner l’une des occurrences, pas nécessairement la première.

Si le ArrayList ne contient pas la valeur spécifiée, la méthode retourne un entier négatif. Vous pouvez appliquer l’opération de complément au niveau du bit (~) à cet entier négatif pour obtenir l’index du premier élément supérieur à la valeur de recherche. Lors de l’insertion de la valeur dans , ArrayListcet index doit être utilisé comme point d’insertion pour conserver l’ordre de tri.

Cette méthode est une O(log n) opération, où n est count.

Voir aussi

S’applique à