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

Description

Array BinarySearch(Array, Int32, Int32, Object) searches a range of elements in a one-dimensional sorted array for a value, using the IComparable interface implemented by each element of the array and by the specified value.

Syntax

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


public static int BinarySearch(
  Array array,/*  ww w  .jav  a  2  s .co  m*/
  int index,
  int length,
  Object value
)

Parameters

Array.BinarySearch(Array, Int32, Int32, Object) 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.

Returns

Array.BinarySearch(Array, Int32, Int32, Object) 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 ww.  ja  v  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.





















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