C# ArrayList BinarySearch(Int32, Int32, Object, IComparer)
Description
ArrayList 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.
Syntax
ArrayList.BinarySearch(Int32, Int32, Object, IComparer)
has the following syntax.
public virtual int BinarySearch(
int index,/*from w w w .j a va 2 s.co m*/
int count,
Object value,
IComparer comparer
)
Parameters
ArrayList.BinarySearch(Int32, Int32, Object, IComparer)
has the following parameters.
index
- The zero-based starting index of the range to search.count
- The length of the range to search.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(Int32, Int32, 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
// w w w . j a v a2 s. c om
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(0,3,"W", new SimpleStringComparer());
Console.WriteLine("Binary search, item found at index: {0}", index);
}
}
The code above generates the following result.