C# Array BinarySearch(Array, Int32, Int32, Object, IComparer)

Description

Array BinarySearch(Array, Int32, Int32, Object, IComparer) searches a range of elements in a one-dimensional sorted array for a value, using the specified IComparer interface.

Syntax

Array.BinarySearch(Array, Int32, Int32, Object, IComparer) has the following syntax.


public static int BinarySearch(
  Array array,/*from   www.j  av a2 s.  c  o m*/
  int index,
  int length,
  Object value,
  IComparer comparer
)

Parameters

Array.BinarySearch(Array, Int32, Int32, Object, IComparer) has the following parameters.

  • array - The sorted one-dimensional Array to search.
  • index - The starting index of the range to search.
  • length - The length of the range to search.
  • value - The object to search for.
  • comparer - The IComparer implementation to use when comparing elements.
  • comparer - -or-
  • comparer - null to use the IComparable implementation of each element.

Returns

Array.BinarySearch(Array, Int32, Int32, Object, IComparer) method returns The index of the specified value in the specified array, if value is found. If value is not found and value is less than one or more elements in array, a negative number which is the bitwise complement of the index of the first element that is larger than value.

Example


/*from   w  w w  .j ava2 s.  c  o m*/
using System;

public class SamplesArray
{
    public static void Main()
    {
        // Creates and initializes a new Array.
        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,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 »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version