Binary search a range of sorted array using the specified IComparer in CSharp
Description
The following code shows how to binary search a range of sorted array using the specified IComparer.
Example
//from w w w . j ava 2s .com
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.