C# ArrayList BinarySearch(Object, IComparer)

Description

ArrayList BinarySearch(Object, IComparer) searches the entire sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.

Syntax

ArrayList.BinarySearch(Object, IComparer) has the following syntax.


public virtual int BinarySearch(
  Object value,
  IComparer comparer
)

Parameters

ArrayList.BinarySearch(Object, IComparer) has the following parameters.

  • value - The Object to locate. The value can be null.
  • comparer - The IComparer implementation to use when comparing elements.
  • comparer - -or-
  • comparer - null to use the default comparer that is the IComparable implementation of each element.

Returns

ArrayList.BinarySearch(Object, IComparer) method 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.

Example

The following example creates an ArrayList of colored animals. The provided IComparer performs the string comparison for the binary search.


/*  www .j a  v  a2  s.com*/
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()
    {
        MyArrayList coloredAnimals = new MyArrayList();

        coloredAnimals.Add("W");
        coloredAnimals.Add("P");
        coloredAnimals.Add("R");
        coloredAnimals.Add("G");
        coloredAnimals.Add("B");
        coloredAnimals.Add("A");
        coloredAnimals.Add("L");

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

The code above generates the following result.





















Home »
  C# Tutorial »
    System.Collections »




ArrayList
BitArray
Comparer
Hashtable
Queue
SortedList
Stack