C# Array BinarySearch(Array, Object)

Description

Array BinarySearch(Array, Object) searches an entire one-dimensional sorted array for a specific element, using the IComparable interface implemented by each element of the array and by the specified object.

Syntax

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


public static int BinarySearch(
  Array array,
  Object value
)

Parameters

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

  • array - The sorted one-dimensional Array to search.
  • value - The object to search for.

Returns

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

If value is not found and value is greater than any of the elements in array, a negative number which is the bitwise complement of (the index of the last element plus 1).

Example

The following code example shows how to use BinarySearch to locate a specific object in an Array.

The array is created with its elements in ascending sort order. The BinarySearch method requires the array to be sorted in ascending order.


/*from   w  ww  .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, 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