C# Array BinarySearch(T[], Int32, Int32, T)
Description
Array BinarySearch (T[], Int32, Int32, T)
searches
a range of elements in a one-dimensional sorted array for a value, using the
IComparable generic interface implemented by each element of the Array
and by the specified value.
Syntax
Array.BinarySearch<T>(T[], Int32, Int32, T)
has the following syntax.
public static int BinarySearch<T>(
T[] array,/*from w w w . j av a 2 s .co m*/
int index,
int length,
T value
)
Parameters
Array.BinarySearch<T>(T[], Int32, Int32, T)
has the following parameters.
T
- The type of the elements of the array.array
- The sorted one-dimensional, zero-based 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<T>(T[], Int32, Int32, 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
/*from w w w. j a v a 2 s. c o m*/
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,0,2, "2015");
ShowWhere(myValues, index);
index = Array.BinarySearch(myValues,0,2, "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.