Binary search sorted array using the IComparable from element in CSharp
Description
The following code shows how to binary search sorted array using the IComparable from element.
Example
/*ww w . j ava 2 s .co m*/
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
string[] myValues = {"2014",
"2015",
"2016",
"2000",
"2002",
"2003"};
Array.Sort(myValues);
foreach( string myValue in myValues )
{
Console.WriteLine(myValue);
}
int index = Array.BinarySearch(myValues, "2015");
ShowWhere(myValues, index);
index = Array.BinarySearch(myValues, "2016");
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.