C# Array BinarySearch(T[], Int32, Int32, T, IComparer)
Description
Array BinarySearch (T[], Int32, Int32, T, IComparer )
searches a range of elements in a one-dimensional sorted
array for a value, using the specified IComparer
Syntax
Array.BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)
has the following syntax.
public static int BinarySearch<T>(
T[] array,//from w ww .j av a 2 s. co m
int index,
int length,
T value,
IComparer<T> comparer
)
Parameters
Array.BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)
has the following parameters.
T
- The type of the elements of the array.array
- The sorted one-dimensional, zero-based Array to search.index
- The starting index of the range to search.length
- The length of the range to search.value
- The object to search for.comparer
- The IComparerimplementation to use when comparing elements. or null to use the IComparableimplementation of each element.
Returns
Array.BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)
method
returns The index of the specified value in the specified array, if value is found.
Example
//from w w w.j av a 2 s. co m
using System;
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] myValues = {"2016",
"1999",
"2001",
"2000",
"2002",
"2003"};
ReverseComparer rc = new ReverseComparer();
Array.Sort(myValues, rc);
foreach( string myValue in myValues )
{
Console.WriteLine(myValue);
}
int index = Array.BinarySearch(myValues, "2011", rc);
ShowWhere(myValues, index);
index = Array.BinarySearch(myValues, "2001", rc);
ShowWhere(myValues, index);
}
private static void ShowWhere<T>(T[] array, int index)
{
if (index<0)
{
index = ~index;
Console.Write("Not found. Sorts between: ");
if (index == 0)
Console.Write("beginning of array and ");
else
Console.Write("{0} and ", array[index-1]);
if (index == array.Length)
Console.WriteLine("end of array.");
else
Console.WriteLine("{0}.", array[index]);
}
else
{
Console.WriteLine("Found at index {0}.", index);
}
}
}
The code above generates the following result.