Binary searchs sorted array with the specified IComparer interface in CSharp

Description

The following code shows how to binary searchs sorted array with the specified IComparer interface.

Example


//from   ww  w.  ja v  a  2  s . c om
using System;

public class SamplesArray
{
    public static void Main()
    {
        Array myIntArray = Array.CreateInstance(typeof(String), 5);

        myIntArray.SetValue("a", 0);
        myIntArray.SetValue("b", 1);
        myIntArray.SetValue("c", 2);
        myIntArray.SetValue("d", 3);
        myIntArray.SetValue("java2s.com", 4);

        Array.Sort(myIntArray);

        object myObjectOdd = "c";
        FindMyObject(myIntArray, myObjectOdd);

    }

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