C# Array BinarySearch(Array, Object, IComparer)
Description
Array BinarySearch(Array, Object, IComparer)
searches
an entire one-dimensional sorted array for a value using the specified IComparer
interface.
Syntax
Array.BinarySearch(Array, Object, IComparer)
has the following syntax.
public static int BinarySearch(
Array array,//from www .ja v a2 s. c o m
Object value,
IComparer comparer
)
Parameters
Array.BinarySearch(Array, Object, IComparer)
has the following parameters.
array
- The sorted one-dimensional Array to search.value
- The object to search for.comparer
- The IComparer implementation to use when comparing elements.comparer
- -or-comparer
- null to use the IComparable implementation of each element.
Returns
Array.BinarySearch(Array, Object, IComparer)
method returns The index of the specified value in the specified array,
if value is found.
Example
//from w ww . ja v a 2 s . com
using System;
public class SamplesArray
{
public static void Main()
{
// Creates and initializes a new Array.
Array myIntArray = Array.CreateInstance(typeof(String), 5);
myIntArray.SetValue("a", 0);
myIntArray.SetValue("b", 1);
myIntArray.SetValue("c", 2);
myIntArray.SetValue("d", 3);
myIntArray.SetValue("java2s.com", 4);
Array.Sort(myIntArray);
object myObjectOdd = "c";
FindMyObject(myIntArray, myObjectOdd);
}
public static void FindMyObject(Array myArr, object myObject)
{
int myIndex=Array.BinarySearch(myArr, myObject,StringComparer.CurrentCulture);
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 );
}
}
}
The code above generates the following result.