Binary searchs sub sorted array with IComparable interface implemented by each element in CSharp
Description
The following code shows how to binary searchs sub sorted array with IComparable interface implemented by each element.
Example
//from w w w . jav a2s. c o m
using System;
public class SamplesArray
{
public static void Main()
{
Array myIntArray = Array.CreateInstance(typeof(Int32), 5);
myIntArray.SetValue(8, 0);
myIntArray.SetValue(2, 1);
myIntArray.SetValue(6, 2);
myIntArray.SetValue(3, 3);
myIntArray.SetValue(7, 4);
Array.Sort(myIntArray);
object myObjectOdd = 1;
FindMyObject( myIntArray, myObjectOdd );
object myObjectEven = 6;
FindMyObject(myIntArray, myObjectEven);
}
public static void FindMyObject(Array myArr, object myObject)
{
int myIndex=Array.BinarySearch(myArr,0,3, myObject);
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.