Array.BinarySearch()方法用于搜索排序的一维数组中的值。该方法使用二进制搜索算法。该算法通过将搜索间隔重复分成两半来搜索排序后的数组。从覆盖整个数组的间隔开始。如果搜索键的值小于间隔中间的项目,则将间隔缩小到下半部分。否则,将其缩小到上半部分。重复检查,直到找到该值或间隔为空。
此方法的重载列表中共有8种方法,如下所示:
- BinarySearch(Array,Object)方法
- BinarySearch(Array,Object,IComparer)方法
- BinarySearch(Array,Int32,Int32,Object)方法
- BinarySearch(Array,Int32,Int32,Object,IComparer)方法
- BinarySearch
(T [],T)方法 - BinarySearch
(T [],T,IComparer )方法 - BinarySearch
(T [],Int32,Int32,T)方法 - BinarySearch
(T [],Int32,Int32,T,IComparer )方法
在这里,在Set-1中已经讨论了前4种方法。本组将讨论最后4种方法
BinarySearch (T [],T)方法
此方法在排序的一维数组中搜索特定元素。它将搜索整个数组。搜索使用IComparable
Syntax: public static int BinarySearch
Here, “T” is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional sorted array to search for.
val: It is the object to search for.
返回值:如果找到val,则返回指定arr中指定val的索引,否则返回负数。返回值有以下几种不同的情况:
- 如果未找到该VAL val是在ARR小于一个或多个元件,所返回的负数是比VAL更大的第一个元素的索引的按位求补。
- 如果没有找到VAL val是比ARR的所有元素时,返回的负数(最后一个元素的索引加1)的位元补码。
- 如果使用非排序数组调用此方法,则即使在arr中存在val ,返回值也可能不正确,并且可能返回负数。
例外情况:
- ArgumentNullException:如果arr为null。
- InvalidOperationException:如果T不实现IComparable
通用接口。
范例1:
// C# program to demonstrate the use of
// BinarySearch(T[], T) method
using System;
using System.Collections.Generic;
class GFG {
// Main Method
public static void Main()
{
string[] arr = {"ABC", "XYZ",
"JKL", "DEF", "MNO"};
Console.WriteLine("Original array");
foreach(string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr);
foreach(string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for 'GHI':");
// call "BinarySearch(T[], T)" method
int index = Array.BinarySearch(arr, "GHI");
sortt(arr, index);
}
// BinarySearch method
private static void sortt(T[] array, int index)
{
if (index < 0)
{
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("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);
}
}
}
Original array
ABC
XYZ
JKL
DEF
MNO
After Sort
ABC
DEF
JKL
MNO
XYZ
BinarySearch for 'GHI':
Sorts between: DEF and JKL.
范例2:
// C# program to demonstrate the use
// of BinarySearch(T[], T) method
using System;
using System.Collections.Generic;
class GFG {
// Main Method
public static void Main()
{
int[] arr = {5, 7, 1, 3, 4, 2};
Console.WriteLine("Original array");
foreach(int g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr);
foreach(int g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for '6':");
// call "BinarySearch(T[], T)" method
int index = Array.BinarySearch(arr, 6);
sortt(arr, index);
}
// BinarySearch method
private static void sortt(T[] array, int index)
{
if (index < 0)
{
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("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);
}
}
}
Original array
5
7
1
3
4
2
After Sort
1
2
3
4
5
7
BinarySearch for '6':
Sorts between: 5 and 7.
BinarySearch (T [],T,IComparer )方法
此方法在使用IComparer
Syntax: public static int BinarySearch
Here, “T” is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional sorted array to search for.
val: It is the object to search for.
comparer: It is theIComparer
返回值:如果找到val,则返回指定arr中指定val的索引,否则返回负数。返回值有以下几种不同的情况:
- 如果未找到该VAL val是在ARR小于一个或多个元件,所返回的负数是比VAL更大的第一个元素的索引的按位求补。
- 如果没有找到VAL val是比ARR的所有元素时,返回的负数(最后一个元素的索引加1)的位元补码。
- 如果使用非排序数组调用此方法,则即使在arr中存在val ,返回值也可能不正确,并且可能返回负数。
例外情况:
- ArgumentNullException:如果数组为null。
- InvalidOperationException:如果比较器为null,并且T不实现IComparable
通用接口。 - ArgumentException:如果比较器为null,并且value是与数组元素不兼容的类型。
例子:
// C# program to demonstrate the use of
// BinarySearch(T[], T, IComparer)
// method
using System;
using System.Collections.Generic;
class comparer : IComparer {
public int Compare(string x, string y)
{
return x.CompareTo(y);
}
}
// Driver Class
class GFG {
// Main Method
public static void Main()
{
string[] arr = {"ABC", "XYZ",
"JKL", "DEF", "MNO"};
Console.WriteLine("Original Array");
foreach(string g in arr)
{
Console.WriteLine(g);
}
// IComparer object
comparer gg = new comparer();
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr, gg);
foreach(string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for 'GHI':");
// search for "GHI"
int index = Array.BinarySearch(arr, "GHI", gg);
sortt(arr, index);
}
// BinarySearch method
private static void sortt(T[] array, int index)
{
if (index < 0) {
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("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);
}
}
}
Original Array
ABC
XYZ
JKL
DEF
MNO
After Sort
ABC
DEF
JKL
MNO
XYZ
BinarySearch for 'GHI':
Sorts between: DEF and JKL
BinarySearch (T [],Int32,Int32,T)
此方法使用由Array的每个元素或指定值实现的IComparable
Syntax: public static int BinarySearch
Here, “T” is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional sorted array to search for.
start: It is the starting index of the range to search.
len: It is the length of the range to search.
val: It is the object to search for.
返回值:如果找到val,则返回指定arr中指定val的索引,否则返回负数。返回值有以下几种不同的情况:
- 如果未找到该VAL val是在ARR小于一个或多个元件,所返回的负数是比VAL更大的第一个元素的索引的按位求补。
- 如果没有找到VAL val是比ARR的所有元素时,返回的负数(最后一个元素的索引加1)的位元补码。
- 如果使用非排序数组调用此方法,则即使在arr中存在val ,返回值也可能不正确,并且可能返回负数。
例外情况:
- ArgumentNullException:如果数组为null。
- InvalidOperationException:如果T不实现IComparable
通用接口。 - ArgumentException:如果start和len没有在数组中指定有效范围,或者value的类型与array的元素不兼容。
- ArgumentOutOfRangeException:如果start小于数组的下限。
例子:
// C# program to demonstrate the use of
// BinarySearch(T[], Int32, Int32,
// T) method
using System;
using System.Collections.Generic;
class GFG {
public static void Main()
{
int[] arr = { 1, 5, 3, 4, 2, 7 };
Console.WriteLine("Original Array");
foreach(int g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr);
foreach(int g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for '6':");
// search for "6" in a
// range of index 0 to 4
int index = Array.BinarySearch(arr, 0, 4, 6);
sortt(arr, index);
}
// BinarySearch method
private static void sortt(T[] array, int index)
{
if (index < 0) {
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("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);
}
}
}
Original Array
1
5
3
4
2
7
After Sort
1
2
3
4
5
7
BinarySearch for '6':
Sorts between: 4 and 5
BinarySearch (T [],Int32,Int32,T,IComparer )方法
此方法使用指定的IComparer
Syntax: public static int BinarySearch
Here, “T” is the type of the elements of the array.
Parameters:
arr: It is the one-dimensional sorted array to search for.
start: It is the starting index of the range to search.
len: It is the length of the range to search.
value: It is the object to search for.
comparer: It is the IComparer
返回值:如果找到val,则返回指定arr中指定val的索引,否则返回负数。返回值有以下几种不同的情况:
- 如果未找到该VAL val是在ARR小于一个或多个元件,所返回的负数是比VAL更大的第一个元素的索引的按位求补。
- 如果没有找到VAL val是比ARR的所有元素时,返回的负数(最后一个元素的索引加1)的位元补码。
- 如果使用非排序数组调用此方法,则即使在arr中存在val ,返回值也可能不正确,并且可能返回负数。
例外情况:
- ArgumentNullException:如果数组为null。
- InvalidOperationException:如果T不实现IComparable
通用接口。 - ArgumentException:如果start和len没有在数组中指定有效范围,或者比较器为null,并且val的类型与数组的元素不兼容。
- ArgumentOutOfRangeException:如果start小于数组的下限,或者len小于零。
例子:
// C# program to demonstrate the use of
// BinarySearch(T[], Int32, Int32,
// T, IComparer) method
using System;
using System.Collections.Generic;
class comparer : IComparer {
public int Compare(string x, string y)
{
return x.CompareTo(y);
}
}
class GFG {
// Main Method
public static void Main()
{
string[] arr = {"ABC", "UVW", "JKL",
"DEF", "MNO", "XYZ"};
Console.WriteLine("Original Array");
foreach(string g in arr)
{
Console.WriteLine(g);
}
// IComparer object
comparer gg = new comparer();
Console.WriteLine("\nAfter Sort");
// sort the array
Array.Sort(arr, gg);
foreach(string g in arr)
{
Console.WriteLine(g);
}
Console.WriteLine("\nBinarySearch for 'GHI':");
// search for "GHI"
// search happens in the
// range of index 1 to 4
int index = Array.BinarySearch(arr, 1, 4, "GHI", gg);
sortt(arr, index);
}
// BinarySearch method
private static void sortt(T[] array, int index)
{
if (index < 0) {
// If the index is negative,
// it represents the bitwise
// complement of the next
// larger element in the array.
index = ~index;
Console.Write("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);
}
}
}
Original Array
ABC
UVW
JKL
DEF
MNO
XYZ
After Sort
ABC
DEF
JKL
MNO
UVW
XYZ
BinarySearch for 'GHI':
Sorts between: DEF and JKL
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.array.binarysearch?view=netframework-4.7.2