Array.BinarySearch 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
利用二元搜尋演算法搜尋一維 Array 排序的值。
多載
| 名稱 | Description |
|---|---|
| BinarySearch(Array, Object) |
利用 IComparable 陣列中每個元素及指定物件所實作的介面,搜尋整個一維排序陣列中的特定元素。 |
| BinarySearch(Array, Object, IComparer) |
利用指定的 IComparer 介面搜尋整個一維排序陣列中的值。 |
| BinarySearch(Array, Int32, Int32, Object) |
利用 IComparable 陣列中每個元素及指定值所實作的介面,在一維排序陣列中搜尋一個值。 |
| BinarySearch(Array, Int32, Int32, Object, IComparer) |
利用指定的 IComparer 介面,在一維排序陣列中搜尋一個值。 |
| BinarySearch<T>(T[], T) |
利用 IComparable<T> 和 中每個元素 Array 所實作的通用介面,搜尋整個一維排序陣列中的特定元素。 |
| BinarySearch<T>(T[], T, IComparer<T>) |
使用指定的 IComparer<T> 通用介面搜尋整個一維排序陣列中的值。 |
| BinarySearch<T>(T[], Int32, Int32, T) |
利用 IComparable<T> 由指定值中每個元素 Array 實作的通用介面,在一維排序陣列中搜尋一個值。 |
| BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>) |
利用指定的 IComparer<T> 通用介面,在一維排序陣列中搜尋一個值。 |
BinarySearch(Array, Object)
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
利用 IComparable 陣列中每個元素及指定物件所實作的介面,搜尋整個一維排序陣列中的特定元素。
public:
static int BinarySearch(Array ^ array, System::Object ^ value);
public static int BinarySearch(Array array, object value);
public static int BinarySearch(Array array, object? value);
static member BinarySearch : Array * obj -> int
Public Shared Function BinarySearch (array As Array, value As Object) As Integer
參數
- value
- Object
要搜尋的物件。
傳回
若找到,則 value 在指定 arrayvalue 中 的索引;否則為負數。 若 value 找不到 value 且小於 中的 array一個或多個元素,則回傳的負數是第一個元素 value索引的位元補數,且該元素大於。 若 value 找不到 value 且大於所有元素 array,則回傳的負數為的位元補數(最後一個元素的索引加1)。 若此方法被非排序 array呼叫,返回值可能錯誤,且可能回傳負數,即使 value 存在於 array。
例外狀況
array 為 null。
array 是多維的。
value 的型別與 的 array元素不相容。
value 未實作介面 IComparable ,搜尋遇到未實作介面 IComparable 的元素。
範例
以下程式碼範例展示了如何使用 BinarySearch 在 中定位特定物件。Array
注意
陣列會以其元素的遞增排序順序建立。 此 BinarySearch 方法要求陣列按升序排序。
open System
let printValues (myArray: Array) =
let mutable i = 0
let cols = myArray.GetLength(myArray.Rank - 1)
for item in myArray do
if i < cols then
i <- i + 1
else
printfn ""
i <- 1;
printf $"\t{item}"
printfn ""
let findMyObject (myArr: Array) (myObject: obj) =
let myIndex = Array.BinarySearch(myArr, myObject)
if myIndex < 0 then
printfn $"The object to search for ({myObject}) is not found. The next larger object is at index {~~~myIndex}."
else
printfn $"The object to search for ({myObject}) is at index {myIndex}."
// Creates and initializes a new Array.
let myIntArray = [| 8; 2; 6; 3; 7 |]
// Do the required sort first
Array.Sort myIntArray
// Displays the values of the Array.
printfn "The int array contains the following:"
printValues myIntArray
// Locates a specific object that does not exist in the Array.
let myObjectOdd: obj = 1
findMyObject myIntArray myObjectOdd
// Locates an object that exists in the Array.
let myObjectEven: obj = 6
findMyObject myIntArray myObjectEven
// This code produces the following output:
// The int array contains the following:
// 2 3 6 7 8
// The object to search for (1) is not found. The next larger object is at index 0.
// The object to search for (6) is at index 2.
using System;
public class SamplesArray
{
public static void Main()
{
// Creates and initializes a new Array.
Array myIntArray = Array.CreateInstance(typeof(int), 5);
myIntArray.SetValue(8, 0);
myIntArray.SetValue(2, 1);
myIntArray.SetValue(6, 2);
myIntArray.SetValue(3, 3);
myIntArray.SetValue(7, 4);
// Do the required sort first
Array.Sort(myIntArray);
// Displays the values of the Array.
Console.WriteLine( "The int array contains the following:" );
PrintValues(myIntArray);
// Locates a specific object that does not exist in the Array.
object myObjectOdd = 1;
FindMyObject( myIntArray, myObjectOdd );
// Locates an object that exists in the Array.
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 );
}
}
public static void PrintValues(Array myArr)
{
int i = 0;
int cols = myArr.GetLength(myArr.Rank - 1);
foreach (object o in myArr)
{
if ( i < cols )
{
i++;
}
else
{
Console.WriteLine();
i = 1;
}
Console.Write( "\t{0}", o);
}
Console.WriteLine();
}
}
// This code produces the following output.
//
//The int array contains the following:
// 2 3 6 7 8
//The object to search for (1) is not found. The next larger object is at index 0
//
//The object to search for (6) is at index 2.
Public Class SamplesArray
Public Shared Sub Main()
' Creates and initializes a new Array.
Dim myIntArray As Array = Array.CreateInstance( GetType(Int32), 5 )
myIntArray.SetValue( 8, 0 )
myIntArray.SetValue( 2, 1 )
myIntArray.SetValue( 6, 2 )
myIntArray.SetValue( 3, 3 )
myIntArray.SetValue( 7, 4 )
' Do the required sort first
Array.Sort(myIntArray)
' Displays the values of the Array.
Console.WriteLine("The Int32 array contains the following:")
PrintValues(myIntArray)
' Locates a specific object that does not exist in the Array.
Dim myObjectOdd As Object = 1
FindMyObject(myIntArray, myObjectOdd)
' Locates an object that exists in the Array.
Dim myObjectEven As Object = 6
FindMyObject(myIntArray, myObjectEven)
End Sub
Public Shared Sub FindMyObject(myArr As Array, myObject As Object)
Dim myIndex As Integer = Array.BinarySearch(myArr, myObject)
If myIndex < 0 Then
Console.WriteLine("The object to search for ({0}) is not found. The next larger object is at index {1}.", myObject, Not(myIndex))
Else
Console.WriteLine("The object to search for ({0}) is at index {1}.", myObject, myIndex)
End If
End Sub
Public Shared Sub PrintValues(myArr As Array)
Dim i As Integer = 0
Dim cols As Integer = myArr.GetLength( myArr.Rank - 1 )
For Each o As Object In myArr
If i < cols Then
i += 1
Else
Console.WriteLine()
i = 1
End If
Console.Write( vbTab + "{0}", o)
Next o
Console.WriteLine()
End Sub
End Class
' This code produces the following output.
'
' The Int32 array contains the following:
' 2 3 6 7 8
' The object to search for (1) is not found. The next larger object is at index 0
'
' The object to search for (6) is at index 2.
備註
此方法不支援搜尋包含負索引的陣列。
array 必須先排序後再呼叫此方法。
若 不 Array 包含指定值,該方法回傳負整數。 你可以對負結果套用位元補數運算子(在 C# 中為 ~ ,Not在 Visual Basic中)來產生索引。 如果這個指標比陣列的上界大一,則陣列中沒有大於 value 該陣列的元素。 否則,就是第一個 value元素的指數大於 。
必須由 的array某一個value或每個元素實作IComparable該介面,該介面用於比較。 元素 array 必須依實作定義 IComparable 的排序順序,依照遞增的值排序;否則結果可能會錯誤。
注意
若value未實作介面,IComparable則在搜尋開始前不會測試 IComparable 的array元素。 若搜尋遇到未實作 IComparable的元素,則會拋出例外。
允許重複的專案。 若 包含 Array 多個元素等於 value,該方法只會回傳其中一個出現的索引,而不一定是第一個。
null 總是可以與其他參考類型比較;因此,與 null 的比較不會產生例外。
注意
對於每個被測試的元素,value即使 是 null,也將 傳遞給適當的IComparable實作value。 也就是說,實 IComparable 作決定了給定元素與 null的比較。
此方法是一個 O(log n) 操作,其中 n 是 Length 的 array。
另請參閱
適用於
BinarySearch(Array, Object, IComparer)
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
利用指定的 IComparer 介面搜尋整個一維排序陣列中的值。
public:
static int BinarySearch(Array ^ array, System::Object ^ value, System::Collections::IComparer ^ comparer);
public static int BinarySearch(Array array, object value, System.Collections.IComparer comparer);
public static int BinarySearch(Array array, object? value, System.Collections.IComparer? comparer);
static member BinarySearch : Array * obj * System.Collections.IComparer -> int
Public Shared Function BinarySearch (array As Array, value As Object, comparer As IComparer) As Integer
參數
- value
- Object
要搜尋的物件。
傳回
若找到,則 value 在指定 arrayvalue 中 的索引;否則為負數。 若 value 找不到 value 且小於 中的 array一個或多個元素,則回傳的負數是第一個元素 value索引的位元補數,且該元素大於。 若 value 找不到 value 且大於所有元素 array,則回傳的負數為的位元補數(最後一個元素的索引加1)。 若此方法被非排序 array呼叫,返回值可能錯誤,且可能回傳負數,即使 value 存在於 array。
例外狀況
array 為 null。
array 是多維的。
comparer 是 null,且 value 的類型與 的 array元素不相容。
comparer 是 null, value 並未實作介面 IComparable ,搜尋遇到的元素未實作該 IComparable 介面。
備註
此方法不支援搜尋包含負索引的陣列。
array 必須先排序後再呼叫此方法。
若 不 Array 包含指定值,該方法回傳負整數。 你可以對負結果套用位元補數運算子(在 C# 中為 ~ ,Not在 Visual Basic中)來產生索引。 如果這個指標比陣列的上界大一,則陣列中沒有大於 value 該陣列的元素。 否則,就是第一個 value元素的指數大於 。
比較子會自定義項目的比較方式。 例如,你可以使用 a System.Collections.CaseInsensitiveComparer 作為比較器來執行大小寫不區分字串的搜尋。
若 comparer 不是 null,則 的 array 元素會與指定的值進行比較,並使用指定的 IComparer 實作。 元素 array 必須依據定義 comparer的排序順序以遞增的值排序;否則,結果可能會不正確。
若comparer 為 null,則使用 IComparable 元素本身提供的實作或指定值進行比較。 元素 array 必須依實作定義 IComparable 的排序順序,依照遞增的值排序;否則結果可能會錯誤。
注意
若 comparer 且 valuenull 未實作介面,IComparable則在搜尋開始前不會測試 IComparable 的array元素。 若搜尋遇到未實作 IComparable的元素,則會拋出例外。
允許重複的專案。 若 包含 Array 多個元素等於 value,該方法只會回傳其中一個出現的索引,而不一定是第一個。
null 總是可以與其他參考類型比較;因此,與 null 的比較不會產生例外。
注意
對於每個被測試的元素,value即使 是 null,也將 傳遞給適當的IComparable實作value。 也就是說,實 IComparable 作決定了給定元素與 null的比較。
此方法是一個 O(log n) 操作,其中 n 是 Length 的 array。
另請參閱
適用於
BinarySearch(Array, Int32, Int32, Object)
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
利用 IComparable 陣列中每個元素及指定值所實作的介面,在一維排序陣列中搜尋一個值。
public:
static int BinarySearch(Array ^ array, int index, int length, System::Object ^ value);
public static int BinarySearch(Array array, int index, int length, object value);
public static int BinarySearch(Array array, int index, int length, object? value);
static member BinarySearch : Array * int * int * obj -> int
Public Shared Function BinarySearch (array As Array, index As Integer, length As Integer, value As Object) As Integer
參數
- index
- Int32
要搜尋之範圍的起始索引。
- length
- Int32
要搜尋的範圍長度。
- value
- Object
要搜尋的物件。
傳回
若找到,則 value 在指定 arrayvalue 中 的索引;否則為負數。 若 value 找不到 value 且小於 中的 array一個或多個元素,則回傳的負數是第一個元素 value索引的位元補數,且該元素大於。 若 value 找不到 value 且大於所有元素 array,則回傳的負數為的位元補數(最後一個元素的索引加1)。 若此方法被非排序 array呼叫,返回值可能錯誤,且可能回傳負數,即使 value 存在於 array。
例外狀況
array 為 null。
array 是多維的。
value 未實作介面 IComparable ,搜尋遇到未實作介面 IComparable 的元素。
備註
此方法不支援搜尋包含負索引的陣列。
array 必須先排序後再呼叫此方法。
若 不 Array 包含指定值,該方法回傳負整數。 你可以對負結果套用位元補數運算子(在 C# 中為 ~ ,Not在 Visual Basic中)來產生索引。 如果這個指標比陣列的上界大一,則陣列中沒有大於 value 該陣列的元素。 否則,就是第一個 value元素的指數大於 。
必須由 的array某一個value或每個元素實作IComparable該介面,該介面用於比較。 元素 array 必須依實作定義 IComparable 的排序順序,依照遞增的值排序;否則結果可能會錯誤。
注意
若value未實作介面,IComparable則在搜尋開始前不會測試 IComparable 的array元素。 若搜尋遇到未實作 IComparable的元素,則會拋出例外。
允許重複的專案。 若 包含 Array 多個元素等於 value,該方法只會回傳其中一個出現的索引,而不一定是第一個。
null 總是可以與其他參考類型比較;因此,與 null 的比較不會產生例外。
注意
對於每個被測試的元素,value即使 是 null,也將 傳遞給適當的IComparable實作value。 也就是說,實 IComparable 作決定了給定元素與 null的比較。
此方法是一個 O(log n) 操作,其中 n 為 length。
另請參閱
適用於
BinarySearch(Array, Int32, Int32, Object, IComparer)
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
利用指定的 IComparer 介面,在一維排序陣列中搜尋一個值。
public:
static int BinarySearch(Array ^ array, int index, int length, System::Object ^ value, System::Collections::IComparer ^ comparer);
public static int BinarySearch(Array array, int index, int length, object value, System.Collections.IComparer comparer);
public static int BinarySearch(Array array, int index, int length, object? value, System.Collections.IComparer? comparer);
static member BinarySearch : Array * int * int * obj * System.Collections.IComparer -> int
Public Shared Function BinarySearch (array As Array, index As Integer, length As Integer, value As Object, comparer As IComparer) As Integer
參數
- index
- Int32
要搜尋之範圍的起始索引。
- length
- Int32
要搜尋的範圍長度。
- value
- Object
要搜尋的物件。
傳回
若找到,則 value 在指定 arrayvalue 中 的索引;否則為負數。 若 value 找不到 value 且小於 中的 array一個或多個元素,則回傳的負數是第一個元素 value索引的位元補數,且該元素大於。 若 value 找不到 value 且大於所有元素 array,則回傳的負數為的位元補數(最後一個元素的索引加1)。 若此方法被非排序 array呼叫,返回值可能錯誤,且可能回傳負數,即使 value 存在於 array。
例外狀況
array 為 null。
array 是多維的。
comparer 是 null, value 並未實作介面 IComparable ,搜尋遇到的元素未實作該 IComparable 介面。
備註
此方法不支援搜尋包含負索引的陣列。
array 必須先排序後再呼叫此方法。
若 不 Array 包含指定值,該方法回傳負整數。 你可以對負結果套用位元補數運算子(在 C# 中為 ~ ,Not在 Visual Basic中)來產生索引。 如果這個指標比陣列的上界大一,則陣列中沒有大於 value 該陣列的元素。 否則,就是第一個 value元素的指數大於 。
比較子會自定義項目的比較方式。 例如,你可以使用 a System.Collections.CaseInsensitiveComparer 作為比較器來執行大小寫不區分字串的搜尋。
若 comparer 不是 null,則 的 array 元素會與指定的值進行比較,並使用指定的 IComparer 實作。 元素 array 必須依據定義 comparer的排序順序以遞增的值排序;否則,結果可能會不正確。
若 comparer 為 null,則使用 IComparable 元素本身提供的實作或指定值進行比較。 元素 array 必須依實作定義 IComparable 的排序順序,依照遞增的值排序;否則結果可能會錯誤。
注意
若 comparer 且 valuenull 未實作介面,IComparable則在搜尋開始前不會測試 IComparable 的array元素。 若搜尋遇到未實作 IComparable的元素,則會拋出例外。
允許重複的專案。 若 包含 Array 多個元素等於 value,該方法只會回傳其中一個出現的索引,而不一定是第一個。
null總是可以與其他參考類型比較;因此,使用 null 與 的比較不會產生例外。IComparable
注意
對於每個被測試的元素,value即使 是 null,也將 傳遞給適當的IComparable實作value。 也就是說,實 IComparable 作決定了給定元素與 null的比較。
此方法是一個 O(log n) 操作,其中 n 為 length。
另請參閱
適用於
BinarySearch<T>(T[], T)
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
利用 IComparable<T> 和 中每個元素 Array 所實作的通用介面,搜尋整個一維排序陣列中的特定元素。
public:
generic <typename T>
static int BinarySearch(cli::array <T> ^ array, T value);
public static int BinarySearch<T>(T[] array, T value);
static member BinarySearch : 'T[] * 'T -> int
Public Shared Function BinarySearch(Of T) (array As T(), value As T) As Integer
類型參數
- T
陣列專案的型別。
參數
- array
- T[]
排序的一維、零基 Array 搜尋。
- value
- T
要搜尋的物件。
傳回
若找到,則 value 在指定 arrayvalue 中 的索引;否則為負數。 若 value 找不到 value 且小於 中的 array一個或多個元素,則回傳的負數是第一個元素 value索引的位元補數,且該元素大於。 若 value 找不到 value 且大於所有元素 array,則回傳的負數為的位元補數(最後一個元素的索引加1)。 若此方法被非排序 array呼叫,返回值可能錯誤,且可能回傳負數,即使 value 存在於 array。
例外狀況
array 為 null。
T 不實作 IComparable<T> 通用介面。
範例
以下程式碼範例展示了 Sort<T>(T[]) 通用方法過載與 BinarySearch<T>(T[], T) 通用方法過載。 系統會建立字串數位,且沒有特定順序。
陣組隨即顯示、排序,並再次顯示。 陣列必須先排序才能使用此 BinarySearch 方法。
注意
呼叫 Sort 和 BinarySearch generic 方法,與非通用方法的呼叫看起來並無差異,因為 Visual Basic、F#、C# 和 C++ 會從第一個參數的類型推導出通用類型參數的類型。 如果你使用 Ildasm.exe(IL 反組譯器)來檢查Microsoft中間語言(MSIL),你可以看到通用方法被呼叫。
BinarySearch<T>(T[], T)接著使用通用方法過載來搜尋兩個字串,一個不在陣列中,一個在陣列中。 陣列與方法的 BinarySearch 回傳值會傳給 ShowWhere 泛型方法( showWhere F# 範例中的函式),若找到該字串,則顯示索引值,否則搜尋字串在陣列中會落入的元素。 若字串不在陣列中,索引為負,因此
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
string[] dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Tyrannosaurus",
"Mamenchisaurus",
"Deinonychus",
"Edmontosaurus"};
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nSort");
Array.Sort(dinosaurs);
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nBinarySearch for 'Coelophysis':");
int index = Array.BinarySearch(dinosaurs, "Coelophysis");
ShowWhere(dinosaurs, index);
Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus");
ShowWhere(dinosaurs, index);
}
private static void ShowWhere<T>(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("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);
}
}
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus
Sort
Amargasaurus
Deinonychus
Edmontosaurus
Mamenchisaurus
Pachycephalosaurus
Tyrannosaurus
BinarySearch for 'Coelophysis':
Not found. Sorts between: Amargasaurus and Deinonychus.
BinarySearch for 'Tyrannosaurus':
Found at index 5.
*/
open System
let showWhere (array: 'a []) index =
if index < 0 then
// If the index is negative, it represents the bitwise
// complement of the next larger element in the array.
let index = ~~~index
printf "Not found. Sorts between: "
if index = 0 then
printf "beginning of array and "
else
printf $"{array[index - 1]} and "
if index = array.Length then
printfn "end of array."
else
printfn $"{array[index]}."
else
printfn $"Found at index {index}."
let dinosaurs =
[| "Pachycephalosaurus"
"Amargasaurus"
"Tyrannosaurus"
"Mamenchisaurus"
"Deinonychus"
"Edmontosaurus" |]
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
printfn "\nSort"
Array.Sort dinosaurs
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
printfn "\nBinarySearch for 'Coelophysis':"
let index = Array.BinarySearch(dinosaurs, "Coelophysis")
showWhere dinosaurs index
printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus")
|> showWhere dinosaurs
// This code example produces the following output:
//
// Pachycephalosaurus
// Amargasaurus
// Tyrannosaurus
// Mamenchisaurus
// Deinonychus
// Edmontosaurus
//
// Sort
//
// Amargasaurus
// Deinonychus
// Edmontosaurus
// Mamenchisaurus
// Pachycephalosaurus
// Tyrannosaurus
//
// BinarySearch for 'Coelophysis':
// Not found. Sorts between: Amargasaurus and Deinonychus.
//
// BinarySearch for 'Tyrannosaurus':
// Found at index 5.
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Pachycephalosaurus", _
"Amargasaurus", _
"Tyrannosaurus", _
"Mamenchisaurus", _
"Deinonychus", _
"Edmontosaurus" }
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & "Sort")
Array.Sort(dinosaurs)
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & _
"BinarySearch for 'Coelophysis':")
Dim index As Integer = _
Array.BinarySearch(dinosaurs, "Coelophysis")
ShowWhere(dinosaurs, index)
Console.WriteLine(vbLf & _
"BinarySearch for 'Tyrannosaurus':")
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus")
ShowWhere(dinosaurs, index)
End Sub
Private Shared Sub ShowWhere(Of T) _
(ByVal array() As T, ByVal index As Integer)
If index < 0 Then
' If the index is negative, it represents the bitwise
' complement of the next larger element in the array.
'
index = index Xor -1
Console.Write("Not found. Sorts between: ")
If index = 0 Then
Console.Write("beginning of array and ")
Else
Console.Write("{0} and ", array(index - 1))
End If
If index = array.Length Then
Console.WriteLine("end of array.")
Else
Console.WriteLine("{0}.", array(index))
End If
Else
Console.WriteLine("Found at index {0}.", index)
End If
End Sub
End Class
' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Tyrannosaurus
'Mamenchisaurus
'Deinonychus
'Edmontosaurus
'
'Sort
'
'Amargasaurus
'Deinonychus
'Edmontosaurus
'Mamenchisaurus
'Pachycephalosaurus
'Tyrannosaurus
'
'BinarySearch for 'Coelophysis':
'Not found. Sorts between: Amargasaurus and Deinonychus.
'
'BinarySearch for 'Tyrannosaurus':
'Found at index 5.
備註
此方法不支援搜尋包含負索引的陣列。
array 必須先排序後再呼叫此方法。
若 array 不包含指定值,則回傳負整數。 你可以對負結果套用位元補數運算子(在 C# 中為 ~ ,Not在 Visual Basic中)來產生索引。 若此索引等於陣列大小,則陣列中沒有大 value 於該陣列的元素。 否則,就是第一個 value元素的指數大於 。
T 必須實作 IComparable<T> 用於比較的通用介面。 元素 array 必須依實作定義 IComparable<T> 的排序順序,依照遞增的值排序;否則結果可能會錯誤。
允許重複的專案。 若 包含 Array 多個元素等於 value,該方法只會回傳其中一個出現的索引,而不一定是第一個。
null 總是可以與其他參考類型比較;因此,與 null 的比較不會產生例外。
注意
對於每個被測試的元素,value即使 是 null,也將 傳遞給適當的IComparable<T>實作value。 也就是說,實 IComparable<T> 作決定了給定元素與 null的比較。
此方法是一個 O(log n) 操作,其中 n 是 Length 的 array。
另請參閱
適用於
BinarySearch<T>(T[], T, IComparer<T>)
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
使用指定的 IComparer<T> 通用介面搜尋整個一維排序陣列中的值。
public:
generic <typename T>
static int BinarySearch(cli::array <T> ^ array, T value, System::Collections::Generic::IComparer<T> ^ comparer);
public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T> comparer);
public static int BinarySearch<T>(T[] array, T value, System.Collections.Generic.IComparer<T>? comparer);
static member BinarySearch : 'T[] * 'T * System.Collections.Generic.IComparer<'T> -> int
Public Shared Function BinarySearch(Of T) (array As T(), value As T, comparer As IComparer(Of T)) As Integer
類型參數
- T
陣列專案的型別。
參數
- array
- T[]
排序的一維、零基 Array 搜尋。
- value
- T
要搜尋的物件。
傳回
若找到,則 value 在指定 arrayvalue 中 的索引;否則為負數。 若 value 找不到 value 且小於 中的 array一個或多個元素,則回傳的負數是第一個元素 value索引的位元補數,且該元素大於。 若 value 找不到 value 且大於所有元素 array,則回傳的負數為的位元補數(最後一個元素的索引加1)。 若此方法被非排序 array呼叫,返回值可能錯誤,且可能回傳負數,即使 value 存在於 array。
例外狀況
array 為 null。
comparer 是 null,且 value 的類型與 的 array元素不相容。
comparer 是 null,且 T 不實作 IComparable<T> 通用介面
範例
以下範例展示了 Sort<T>(T[], IComparer<T>) 通用方法過載與 BinarySearch<T>(T[], T, IComparer<T>) 通用方法過載。
程式碼範例定義了一個字串的替代比較器,名為 ReverseCompare,實作了 IComparer<string>(在 Visual Basic 中稱為 IComparer(Of String))通用介面。 比較器呼叫該 CompareTo(String) 方法,將比較順序反轉,使字串依高至低排序,而非低至高。
陣組隨即顯示、排序,並再次顯示。 陣列必須先排序才能使用此 BinarySearch 方法。
注意
Sort<T>(T[], IComparer<T>) 和 BinarySearch<T>(T[], T, IComparer<T>) 通用方法的呼叫與非通用方法的呼叫看起來並無差異,因為 Visual Basic、C# 和 C++ 是從第一個參數的類型推斷出通用類型參數的類型。 如果你使用 Ildasm.exe(IL 反組譯器)來檢查Microsoft中間語言(MSIL),你可以看到通用方法被呼叫。
BinarySearch<T>(T[], T, IComparer<T>)接著使用通用方法過載來搜尋兩個字串,一個不在陣列中,一個在陣列中。 陣列與方法的 BinarySearch<T>(T[], T, IComparer<T>) 回傳值會傳給 ShowWhere 泛型方法( showWhere F# 範例中的函式),若找到該字串,則顯示索引值,否則搜尋字串在陣列中會落入的元素。 若字串不在陣列中,索引為負,因此
using System;
using System.Collections.Generic;
public class ReverseComparer: IComparer<string>
{
public int Compare(string x, string y)
{
// Compare y and x in reverse order.
return y.CompareTo(x);
}
}
public class Example
{
public static void Main()
{
string[] dinosaurs = {"Pachycephalosaurus",
"Amargasaurus",
"Tyrannosaurus",
"Mamenchisaurus",
"Deinonychus",
"Edmontosaurus"};
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
ReverseComparer rc = new ReverseComparer();
Console.WriteLine("\nSort");
Array.Sort(dinosaurs, rc);
Console.WriteLine();
foreach( string dinosaur in dinosaurs )
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nBinarySearch for 'Coelophysis':");
int index = Array.BinarySearch(dinosaurs, "Coelophysis", rc);
ShowWhere(dinosaurs, index);
Console.WriteLine("\nBinarySearch for 'Tyrannosaurus':");
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc);
ShowWhere(dinosaurs, index);
}
private static void ShowWhere<T>(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("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);
}
}
}
/* This code example produces the following output:
Pachycephalosaurus
Amargasaurus
Tyrannosaurus
Mamenchisaurus
Deinonychus
Edmontosaurus
Sort
Tyrannosaurus
Pachycephalosaurus
Mamenchisaurus
Edmontosaurus
Deinonychus
Amargasaurus
BinarySearch for 'Coelophysis':
Not found. Sorts between: Deinonychus and Amargasaurus.
BinarySearch for 'Tyrannosaurus':
Found at index 0.
*/
open System
open System.Collections.Generic
type ReverseComparer() =
interface IComparer<string> with
member _.Compare(x, y) =
// Compare y and x in reverse order.
y.CompareTo x
let showWhere (array: 'a []) index =
if index < 0 then
// If the index is negative, it represents the bitwise
// complement of the next larger element in the array.
let index = ~~~index
printf "Not found. Sorts between: "
if index = 0 then
printf "beginning of array and "
else
printf $"{array[index - 1]} and "
if index = array.Length then
printfn "end of array."
else
printfn $"{array[index]}."
else
printfn $"Found at index {index}."
let dinosaurs =
[| "Pachycephalosaurus"
"Amargasaurus"
"Tyrannosaurus"
"Mamenchisaurus"
"Deinonychus"
"Edmontosaurus" |]
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
let rc = ReverseComparer()
printfn "\nSort"
Array.Sort(dinosaurs, rc)
printfn ""
for dino in dinosaurs do
printfn $"{dino}"
printfn "\nBinarySearch for 'Coelophysis':"
Array.BinarySearch(dinosaurs, "Coelophysis", rc)
|> showWhere dinosaurs
printfn "\nBinarySearch for 'Tyrannosaurus':"
Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
|> showWhere dinosaurs
// This code example produces the following output:
// Pachycephalosaurus
// Amargasaurus
// Tyrannosaurus
// Mamenchisaurus
// Deinonychus
// Edmontosaurus
//
// Sort
//
// Tyrannosaurus
// Pachycephalosaurus
// Mamenchisaurus
// Edmontosaurus
// Deinonychus
// Amargasaurus
//
// BinarySearch for 'Coelophysis':
// Not found. Sorts between: Deinonychus and Amargasaurus.
//
// BinarySearch for 'Tyrannosaurus':
// Found at index 0.
Imports System.Collections.Generic
Public Class ReverseComparer
Implements IComparer(Of String)
Public Function Compare(ByVal x As String, _
ByVal y As String) As Integer _
Implements IComparer(Of String).Compare
' Compare y and x in reverse order.
Return y.CompareTo(x)
End Function
End Class
Public Class Example
Public Shared Sub Main()
Dim dinosaurs() As String = { _
"Pachycephalosaurus", _
"Amargasaurus", _
"Tyrannosaurus", _
"Mamenchisaurus", _
"Deinonychus", _
"Edmontosaurus" }
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Dim rc As New ReverseComparer()
Console.WriteLine(vbLf & "Sort")
Array.Sort(dinosaurs, rc)
Console.WriteLine()
For Each dinosaur As String In dinosaurs
Console.WriteLine(dinosaur)
Next
Console.WriteLine(vbLf & _
"BinarySearch for 'Coelophysis':")
Dim index As Integer = _
Array.BinarySearch(dinosaurs, "Coelophysis", rc)
ShowWhere(dinosaurs, index)
Console.WriteLine(vbLf & _
"BinarySearch for 'Tyrannosaurus':")
index = Array.BinarySearch(dinosaurs, "Tyrannosaurus", rc)
ShowWhere(dinosaurs, index)
End Sub
Private Shared Sub ShowWhere(Of T) _
(ByVal array() As T, ByVal index As Integer)
If index < 0 Then
' If the index is negative, it represents the bitwise
' complement of the next larger element in the array.
'
index = index Xor -1
Console.Write("Not found. Sorts between: ")
If index = 0 Then
Console.Write("beginning of array and ")
Else
Console.Write("{0} and ", array(index - 1))
End If
If index = array.Length Then
Console.WriteLine("end of array.")
Else
Console.WriteLine("{0}.", array(index))
End If
Else
Console.WriteLine("Found at index {0}.", index)
End If
End Sub
End Class
' This code example produces the following output:
'
'Pachycephalosaurus
'Amargasaurus
'Tyrannosaurus
'Mamenchisaurus
'Deinonychus
'Edmontosaurus
'
'Sort
'
'Tyrannosaurus
'Pachycephalosaurus
'Mamenchisaurus
'Edmontosaurus
'Deinonychus
'Amargasaurus
'
'BinarySearch for 'Coelophysis':
'Not found. Sorts between: Deinonychus and Amargasaurus.
'
'BinarySearch for 'Tyrannosaurus':
'Found at index 0.
備註
此方法不支援搜尋包含負索引的陣列。
array 必須先排序後再呼叫此方法。
若 不 Array 包含指定值,該方法回傳負整數。 你可以對負結果套用位元補數運算子(在 C# 中為 ~ ,Not在 Visual Basic中)來產生索引。 若此索引等於陣列大小,則陣列中沒有大 value 於該陣列的元素。 否則,就是第一個 value元素的指數大於 。
比較子會自定義項目的比較方式。 例如,你可以使用 a System.Collections.CaseInsensitiveComparer 作為比較器來執行大小寫不區分字串的搜尋。
若 comparer 不是null,則使用 指定的IComparer<T>通用介面實作將 的array元素與指定值比較。 元素 array 必須依據定義 comparer的排序順序以遞增的值排序;否則,結果可能會不正確。
若 comparer 是 null,則使用 IComparable<T> 由 T提供的通用介面實作進行比較。 元素 array 必須依實作定義 IComparable<T> 的排序順序,依照遞增的值排序;否則結果可能會錯誤。
注意
若 comparer 且 nullvalue 未實作IComparable<T>通用介面,則在搜尋開始前不會測試 IComparable<T> 的array元素。 若搜尋遇到未實作 IComparable<T>的元素,則會拋出例外。
允許重複的專案。 若 包含 Array 多個元素等於 value,該方法只會回傳其中一個出現的索引,而不一定是第一個。
null 總是可以與其他參考類型比較;因此,與 null 的比較不會產生例外。
注意
對於每個被測試的元素,value即使 是 null,也將 傳遞給適當的IComparable<T>實作value。 也就是說,實 IComparable<T> 作決定了給定元素與 null的比較。
此方法是一個 O(log n) 操作,其中 n 是 Length 的 array。
另請參閱
適用於
BinarySearch<T>(T[], Int32, Int32, T)
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
利用 IComparable<T> 由指定值中每個元素 Array 實作的通用介面,在一維排序陣列中搜尋一個值。
public:
generic <typename T>
static int BinarySearch(cli::array <T> ^ array, int index, int length, T value);
public static int BinarySearch<T>(T[] array, int index, int length, T value);
static member BinarySearch : 'T[] * int * int * 'T -> int
Public Shared Function BinarySearch(Of T) (array As T(), index As Integer, length As Integer, value As T) As Integer
類型參數
- T
陣列專案的型別。
參數
- array
- T[]
排序的一維、零基 Array 搜尋。
- index
- Int32
要搜尋之範圍的起始索引。
- length
- Int32
要搜尋的範圍長度。
- value
- T
要搜尋的物件。
傳回
若找到,則 value 在指定 arrayvalue 中 的索引;否則為負數。 若 value 找不到 value 且小於 中的 array一個或多個元素,則回傳的負數是第一個元素 value索引的位元補數,且該元素大於。 若 value 找不到 value 且大於所有元素 array,則回傳的負數為的位元補數(最後一個元素的索引加1)。 若此方法被非排序 array呼叫,返回值可能錯誤,且可能回傳負數,即使 value 存在於 array。
例外狀況
array 為 null。
T 不實作 IComparable<T> 通用介面。
備註
此方法不支援搜尋包含負索引的陣列。
array 必須先排序後再呼叫此方法。
如果陣列不包含指定的值,此方法會傳回負整數。 你可以對負結果套用位元補數運算子(在 C# 中為 ~ ,Not在 Visual Basic中)來產生索引。 若此索引等於陣列大小,則陣列中沒有大 value 於該陣列的元素。 否則,就是第一個 value元素的指數大於 。
T 必須實作 IComparable<T> 用於比較的通用介面。 元素 array 必須依實作定義 IComparable<T> 的排序順序,依照遞增的值排序;否則結果可能會錯誤。
允許重複的專案。 若 包含 Array 多個元素等於 value,該方法只會回傳其中一個出現的索引,而不一定是第一個。
null 總是可以與其他參考類型比較;因此,與 null 的比較不會產生例外。
注意
對於每個被測試的元素,value即使 是 null,也將 傳遞給適當的IComparable<T>實作value。 也就是說,實 IComparable<T> 作決定了給定元素與 null的比較。
此方法是一個 O(log n) 操作,其中 n 為 length。
另請參閱
適用於
BinarySearch<T>(T[], Int32, Int32, T, IComparer<T>)
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
- 來源:
- Array.cs
利用指定的 IComparer<T> 通用介面,在一維排序陣列中搜尋一個值。
public:
generic <typename T>
static int BinarySearch(cli::array <T> ^ array, int index, int length, T value, System::Collections::Generic::IComparer<T> ^ comparer);
public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T> comparer);
public static int BinarySearch<T>(T[] array, int index, int length, T value, System.Collections.Generic.IComparer<T>? comparer);
static member BinarySearch : 'T[] * int * int * 'T * System.Collections.Generic.IComparer<'T> -> int
Public Shared Function BinarySearch(Of T) (array As T(), index As Integer, length As Integer, value As T, comparer As IComparer(Of T)) As Integer
類型參數
- T
陣列專案的型別。
參數
- array
- T[]
排序的一維、零基 Array 搜尋。
- index
- Int32
要搜尋之範圍的起始索引。
- length
- Int32
要搜尋的範圍長度。
- value
- T
要搜尋的物件。
傳回
若找到,則 value 在指定 arrayvalue 中 的索引;否則為負數。 若 value 找不到 value 且小於 中的 array一個或多個元素,則回傳的負數是第一個元素 value索引的位元補數,且該元素大於。 若 value 找不到 value 且大於所有元素 array,則回傳的負數為的位元補數(最後一個元素的索引加1)。 若此方法被非排序 array呼叫,返回值可能錯誤,且可能回傳負數,即使 value 存在於 array。
例外狀況
array 為 null。
comparer 是 null,且 T 不實作 IComparable<T> 通用介面。
備註
此方法不支援搜尋包含負索引的陣列。
array 必須先排序後再呼叫此方法。
如果陣列不包含指定的值,此方法會傳回負整數。 你可以對負結果套用位元補數運算子(在 C# 中為 ~ ,Not在 Visual Basic中)來產生索引。 若此索引等於陣列大小,則陣列中沒有大 value 於該陣列的元素。 否則,就是第一個 value元素的指數大於 。
比較子會自定義項目的比較方式。 例如,你可以使用 a System.Collections.CaseInsensitiveComparer 作為比較器來執行大小寫不區分字串的搜尋。
若 comparer 不是null,則使用 指定的IComparer<T>通用介面實作將 的array元素與指定值比較。 元素 array 必須依據定義 comparer的排序順序以遞增的值排序;否則,結果可能會不正確。
若 comparer 為 null,則使用 IComparable<T> 類型 T所提供的通用介面實作進行比較。 元素 array 必須依實作定義 IComparable<T> 的排序順序,依照遞增的值排序;否則結果可能會錯誤。
允許重複的專案。 若 包含 Array 多個元素等於 value,該方法只會回傳其中一個出現的索引,而不一定是第一個。
null總是可以與其他參考類型比較;因此,使用 null 與 的比較不會產生例外。IComparable<T>
注意
對於每個被測試的元素,value即使 是 null,也將 傳遞給適當的IComparable<T>實作value。 也就是說,實 IComparable<T> 作決定了給定元素與 null的比較。
此方法是一個 O(log n) 操作,其中 n 為 length。