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.

C#
public virtual int BinarySearch(object value);
C#
public virtual int BinarySearch(object? value);

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.

C#
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.
*/

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

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

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.

C#
public virtual int BinarySearch(object value, System.Collections.IComparer comparer);
C#
public virtual int BinarySearch(object? value, System.Collections.IComparer? comparer);

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.

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

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

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

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.

C#
public virtual int BinarySearch(int index, int count, object value, System.Collections.IComparer comparer);
C#
public virtual int BinarySearch(int index, int count, object? value, System.Collections.IComparer? comparer);

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

.NET 9 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0