Binary Searche sorted array using the IComparable from each element in CSharp

Description

The following code shows how to binary Searche sorted array using the IComparable from each element.

Example


//from   w w  w  . j a va  2  s  .  co m
using System;

public class SamplesArray
{
    public static void Main()
    {
        int[] intArray = new int[] { 1, 2, 4 };
        Array.Sort(intArray);

        object myObjectOdd = 1;
        FindMyObject( intArray, myObjectOdd );

        object myObjectEven = 6;
        FindMyObject(intArray, myObjectEven);
    }

    public static void FindMyObject(Array myArr, object myObject)
    {
        int myIndex=Array.BinarySearch(myArr, 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.





















Home »
  C# Tutorial »
    Data Types »




C# Data Types
Bool
Byte
Char
Decimal
Double
Float
Integer
Long
Short
String
C# Array
Array Example
Byte Array
C# Standard Data Type Format
BigInteger
Complex
Currency
DateTime
DateTimeOffset
DateTime Format Parse Convert
TimeSpan
TimeZone
Enum
Null
tuple
var