C# Array BinarySearch(T[], T)

Description

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

Syntax

Array.BinarySearch<T>(T[], T) has the following syntax.


public static int BinarySearch<T>(
  T[] array,
  T value
)

Parameters

Array.BinarySearch<T>(T[], T) has the following parameters.

  • T - The type of the elements of the array.
  • array - The sorted one-dimensional, zero-based Array to search.
  • value - The object to search for.

Returns

Array.BinarySearch<T>(T[], T) 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

The following code example demonstrates the Sort<T>(T[]) generic method overload and the BinarySearch<T>(T[], T) generic method overload.


//from www  .ja v a 2s  . c om
using System;
using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        string[] myValues = {"2014", 
                              "2015", 
                              "2016", 
                              "2000", 
                              "2002", 
                              "2003"};

        Array.Sort(myValues);
        foreach( string myValue in myValues )
        {
            Console.WriteLine(myValue);
        }

        int index = Array.BinarySearch(myValues, "2015");
        ShowWhere(myValues, index);

        index = Array.BinarySearch(myValues, "2016");
        ShowWhere(myValues, index);
    }

    private static void ShowWhere<T>(T[] array, int index)
    {
        if (index<0)
        {
            index = ~index;

            Console.Write("Not found. Sorts between: ");

            if (index == 0)
                Console.Write("beginning of array and ");
            else
                Console.Write("{0} and ", array[index-1]);

            if (index == array.Length)
                Console.WriteLine("end of array.");
            else
                Console.WriteLine("{0}.", array[index]);
        }
        else
        {
            Console.WriteLine("Found at index {0}.", index);
        }
    }
}

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