ArrayList.BinarySearch 方法

定義

使用二進位搜尋演算法來尋找在排序的 ArrayList 中或在其中一部分中的特定項目。

多載

BinarySearch(Object)

使用預設的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 ArrayList

BinarySearch(Object, IComparer)

使用指定的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 ArrayList

BinarySearch(Int32, Int32, Object, IComparer)

使用指定的比較子在已經過排序之 ArrayList 內,搜尋某範圍的項目,並傳回該項目以零為起始的索引。

BinarySearch(Object)

來源:
ArrayList.cs
來源:
ArrayList.cs
來源:
ArrayList.cs

使用預設的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 ArrayList

public:
 virtual int BinarySearch(System::Object ^ value);
public virtual int BinarySearch (object value);
public virtual int BinarySearch (object? value);
abstract member BinarySearch : obj -> int
override this.BinarySearch : obj -> int
Public Overridable Function BinarySearch (value As Object) As Integer

參數

value
Object

要尋找的 Object。 這個值可以是 null

傳回

如果找到 value,則為已排序的 ArrayListvalue 之以零為起使的索引,否則為負數,即大於 value 的下一個項目索引之位元補數,或者,如果沒有更大的項目,則為 Count 的位元補數。

例外狀況

valueArrayList 的項目都不能實作 IComparable 介面。

value 的類型與 ArrayList 的項目類型不同。

範例

下列程式代碼範例示範如何使用 BinarySearch 來尋找 中的 ArrayList特定物件。

using namespace System;
using namespace System::Collections;
void FindMyObject( ArrayList^ myList, Object^ myObject );
void PrintValues( IEnumerable^ myList );
int main()
{
   
   // Creates and initializes a new ArrayList. BinarySearch requires
   // a sorted ArrayList.
   ArrayList^ myAL = gcnew ArrayList;
   for ( int i = 0; i <= 4; i++ )
      myAL->Add( i * 2 );
   
   // Displays the ArrayList.
   Console::WriteLine( "The Int32 ArrayList contains the following:" );
   PrintValues( myAL );
   
   // Locates a specific object that does not exist in the ArrayList.
   Object^ myObjectOdd = 3;
   FindMyObject( myAL, myObjectOdd );
   
   // Locates an object that exists in the ArrayList.
   Object^ myObjectEven = 6;
   FindMyObject( myAL, myObjectEven );
}

void FindMyObject( ArrayList^ myList, Object^ myObject )
{
   int myIndex = myList->BinarySearch( 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 );
}

void PrintValues( IEnumerable^ myList )
{
   IEnumerator^ myEnum = myList->GetEnumerator();
   while ( myEnum->MoveNext() )
   {
      Object^ obj = safe_cast<Object^>(myEnum->Current);
      Console::Write( "   {0}", obj );
   }

   Console::WriteLine();
}

/* 
 This code produces the following output.
 
 The Int32 ArrayList contains the following:
    0   2   4   6   8
 The object to search for (3) is not found. The next larger object is at index 2.
 The object to search for (6) is at index 3.
 */
using System;
using System.Collections;
public class SamplesArrayList  {

   public static void Main()  {

      // Creates and initializes a new ArrayList. BinarySearch requires
      // a sorted ArrayList.
      ArrayList myAL = new ArrayList();
      for ( int i = 0; i <= 4; i++ )
         myAL.Add( i*2 );

      // Displays the ArrayList.
      Console.WriteLine( "The int ArrayList contains the following:" );
      PrintValues( myAL );

      // Locates a specific object that does not exist in the ArrayList.
      Object myObjectOdd = 3;
      FindMyObject( myAL, myObjectOdd );

      // Locates an object that exists in the ArrayList.
      Object myObjectEven = 6;
      FindMyObject( myAL, myObjectEven );
   }

   public static void FindMyObject( ArrayList myList, Object myObject )  {
      int myIndex=myList.BinarySearch( 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( IEnumerable myList )  {
      foreach ( Object obj in myList )
         Console.Write( "   {0}", obj );
      Console.WriteLine();
   }
}
/*
This code produces the following output.

The int ArrayList contains the following:
   0   2   4   6   8
The object to search for (3) is not found. The next larger object is at index 2.
The object to search for (6) is at index 3.
*/
Imports System.Collections

Public Class SamplesArrayList    
    
    Public Shared Sub Main()
        
        ' Creates and initializes a new ArrayList. BinarySearch requires
        ' a sorted ArrayList.
        Dim myAL As New ArrayList()
        Dim i As Integer
        For i = 0 To 4
            myAL.Add(i * 2)
        Next i 

        ' Displays the ArrayList.
        Console.WriteLine("The Int32 ArrayList contains the following:")
        PrintValues(myAL)
        
        ' Locates a specific object that does not exist in the ArrayList.
        Dim myObjectOdd As Object = 3
        FindMyObject(myAL, myObjectOdd)
        
        ' Locates an object that exists in the ArrayList.
        Dim myObjectEven As Object = 6
        FindMyObject(myAL, myObjectEven)
    End Sub    
    
    Public Shared Sub FindMyObject(myList As ArrayList, myObject As Object)
        Dim myIndex As Integer = myList.BinarySearch(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(myList As IEnumerable)
        Dim obj As [Object]
        For Each obj In  myList
            Console.Write("   {0}", obj)
        Next obj
        Console.WriteLine()
    End Sub
    
End Class

' This code produces the following output.
' 
' The Int32 ArrayList contains the following:
'     0    2    4    6    8
' The object to search for (3) is not found. The next larger object is at index 2.
' The object to search for (6) is at index 3.

備註

的參數 value 和 的每個 ArrayList 元素都必須實 IComparable 作 介面,以便進行比較。 的元素 ArrayList 必須已根據實作所 IComparable 定義的排序順序,以遞增值排序;否則結果可能不正確。

null允許與任何類型比較,且在使用 IComparable時不會產生例外狀況。 排序時, null 會被視為小於任何其他物件。

ArrayList如果 包含多個具有相同值的專案,則方法只會傳回其中一個出現專案,而且可能會傳回任何一個出現專案,不一定傳回第一個專案。

ArrayList如果 不包含指定的值,則方法會傳回負整數。 您可以將位補碼運算 (~) 套用至這個負整數,以取得大於搜尋值的第一個專案索引。 將值插入 至 ArrayList時,這個索引應該當做插入點使用,以維護排序順序。

這個方法是作業 O(log n) ,其中 nCount

另請參閱

適用於

BinarySearch(Object, IComparer)

來源:
ArrayList.cs
來源:
ArrayList.cs
來源:
ArrayList.cs

使用指定的比較子並傳回項目以零為起始的索引,來搜尋項目之整個排序的 ArrayList

public:
 virtual int BinarySearch(System::Object ^ value, System::Collections::IComparer ^ comparer);
public virtual int BinarySearch (object value, System.Collections.IComparer comparer);
public virtual int BinarySearch (object? value, System.Collections.IComparer? comparer);
abstract member BinarySearch : obj * System.Collections.IComparer -> int
override this.BinarySearch : obj * System.Collections.IComparer -> int
Public Overridable Function BinarySearch (value As Object, comparer As IComparer) As Integer

參數

value
Object

要尋找的 Object。 這個值可以是 null

comparer
IComparer

比較項目時所要使用的 IComparer 實作。

-或-

要使用預設比較子的 null 是每個項目的 IComparable 實作。

傳回

如果找到 value,則為已排序的 ArrayListvalue 之以零為起使的索引,否則為負數,即大於 value 的下一個項目索引之位元補數,或者,如果沒有更大的項目,則為 Count 的位元補數。

例外狀況

comparernull,而且 valueArrayList 的項目都不能實作 IComparable 介面。

comparernullvalue 的類型與 ArrayList 的項目類型不同。

範例

下列範例會 ArrayList 建立彩色動物的 。 提供的 IComparer 會執行二進位搜尋的字串比較。 會顯示反覆搜尋和二進位搜尋的結果。

using namespace System;
using namespace System::Collections;

public ref class SimpleStringComparer : public IComparer
{
    virtual int Compare(Object^ x, Object^ y) sealed = IComparer::Compare
    {
        String^ cmpstr = (String^)x;
        return cmpstr->CompareTo((String^)y);
    }
};

public ref class MyArrayList : public ArrayList
{
public:
    static void Main()
    {
        // Creates and initializes a new ArrayList.
        MyArrayList^ coloredAnimals = gcnew MyArrayList();

        coloredAnimals->Add("White Tiger");
        coloredAnimals->Add("Pink Bunny");
        coloredAnimals->Add("Red Dragon");
        coloredAnimals->Add("Green Frog");
        coloredAnimals->Add("Blue Whale");
        coloredAnimals->Add("Black Cat");
        coloredAnimals->Add("Yellow Lion");

        // BinarySearch requires a sorted ArrayList.
        coloredAnimals->Sort();

        // Compare results of an iterative search with a binary search
        int index = coloredAnimals->IterativeSearch("White Tiger");
        Console::WriteLine("Iterative search, item found at index: {0}", index);

        index = coloredAnimals->BinarySearch("White Tiger", gcnew SimpleStringComparer());
        Console::WriteLine("Binary search, item found at index:    {0}", index);
    }

    int IterativeSearch(Object^ finditem)
    {
        int index = -1;

        for (int i = 0; i < this->Count; i++)
        {
            if (finditem->Equals(this[i]))
            {
                index = i;
                break;
            }
        }
        return index;
    }
};

int main()
{
    MyArrayList::Main();
}
//
// This code produces the following output.
//
// Iterative search, item found at index: 5
// Binary search, item found at index:    5
//
using System;
using System.Collections;

public class SimpleStringComparer : IComparer
{
    int IComparer.Compare(object x, object y)
    {
        string cmpstr = (string)x;
        return cmpstr.CompareTo((string)y);
    }
}

public class MyArrayList : ArrayList
{
    public static void Main()
    {
        // Creates and initializes a new ArrayList.
        MyArrayList coloredAnimals = new MyArrayList();

        coloredAnimals.Add("White Tiger");
        coloredAnimals.Add("Pink Bunny");
        coloredAnimals.Add("Red Dragon");
        coloredAnimals.Add("Green Frog");
        coloredAnimals.Add("Blue Whale");
        coloredAnimals.Add("Black Cat");
        coloredAnimals.Add("Yellow Lion");

        // BinarySearch requires a sorted ArrayList.
        coloredAnimals.Sort();

        // Compare results of an iterative search with a binary search
        int index = coloredAnimals.IterativeSearch("White Tiger");
        Console.WriteLine("Iterative search, item found at index: {0}", index);

        index = coloredAnimals.BinarySearch("White Tiger", new SimpleStringComparer());
        Console.WriteLine("Binary search, item found at index:    {0}", index);
    }

    public int IterativeSearch(object finditem)
    {
        int index = -1;

        for (int i = 0; i < this.Count; i++)
        {
            if (finditem.Equals(this[i]))
            {
                index = i;
                break;
            }
        }
        return index;
    }
}
//
// This code produces the following output.
//
// Iterative search, item found at index: 5
// Binary search, item found at index:    5
//
Imports System.Collections

Public Class SimpleStringComparer
    Implements IComparer

    Function Compare(x As Object, y As Object) As Integer Implements IComparer.Compare
          Dim cmpstr As String = CType(x, String)
          Return cmpstr.CompareTo(CType(y, String))
    End Function
End Class

Public Class MyArrayList
    Inherits ArrayList

    Public Shared Sub Main()
        ' Creates and initializes a new ArrayList.
        Dim coloredAnimals As New MyArrayList()

        coloredAnimals.Add("White Tiger")
        coloredAnimals.Add("Pink Bunny")
        coloredAnimals.Add("Red Dragon")
        coloredAnimals.Add("Green Frog")
        coloredAnimals.Add("Blue Whale")
        coloredAnimals.Add("Black Cat")
        coloredAnimals.Add("Yellow Lion")

        ' BinarySearch requires a sorted ArrayList.
        coloredAnimals.Sort()

        ' Compare results of an iterative search with a binary search
        Dim index As Integer = coloredAnimals.IterativeSearch("White Tiger")
        Console.WriteLine("Iterative search, item found at index: {0}", index)

        index = coloredAnimals.BinarySearch("White Tiger", New SimpleStringComparer())
        Console.WriteLine("Binary search, item found at index:    {0}", index)
    End Sub

    Public Function IterativeSearch(finditem As Object) As Integer
        Dim index As Integer = -1

        For i As Integer = 0 To MyClass.Count - 1
            If finditem.Equals(MyClass.Item(i))
                index = i
                Exit For
            End If
        Next i
        Return index
    End Function
End Class
'
' This code produces the following output.
'
' Iterative search, item found at index: 5
' Binary search, item found at index:    5
'

備註

比較子會自定義元素的比較方式。 例如,您可以使用 CaseInsensitiveComparer 實例作為比較子來執行不區分大小寫的字串搜尋。

如果 comparer 已提供 ,則會使用指定的實作,將的 ArrayList 元素與指定的 IComparer 值進行比較。 ArrayList的項目必須已根據 所comparer定義的排序順序,以遞增值排序;否則結果可能不正確。

如果 為 comparernull,則比較是使用 IComparable 專案本身或指定值所提供的實作來完成。 的元素 ArrayList 必須已根據實作所 IComparable 定義的排序順序,以遞增值排序;否則結果可能不正確。

null允許與任何類型比較,且在使用 IComparable時不會產生例外狀況。 排序時, null 會被視為小於任何其他物件。

ArrayList如果 包含多個具有相同值的專案,則方法只會傳回其中一個出現專案,而且可能會傳回任何一個出現專案,不一定傳回第一個專案。

ArrayList如果 不包含指定的值,則方法會傳回負整數。 您可以將位補碼運算 (~) 套用至這個負整數,以取得大於搜尋值的第一個專案索引。 將值插入 至 ArrayList時,這個索引應該當做插入點使用,以維護排序順序。

這個方法是作業 O(log n) ,其中 nCount

另請參閱

適用於

BinarySearch(Int32, Int32, Object, IComparer)

來源:
ArrayList.cs
來源:
ArrayList.cs
來源:
ArrayList.cs

使用指定的比較子在已經過排序之 ArrayList 內,搜尋某範圍的項目,並傳回該項目以零為起始的索引。

public:
 virtual int BinarySearch(int index, int count, System::Object ^ value, System::Collections::IComparer ^ comparer);
public virtual int BinarySearch (int index, int count, object value, System.Collections.IComparer comparer);
public virtual int BinarySearch (int index, int count, object? value, System.Collections.IComparer? comparer);
abstract member BinarySearch : int * int * obj * System.Collections.IComparer -> int
override this.BinarySearch : int * int * obj * System.Collections.IComparer -> int
Public Overridable Function BinarySearch (index As Integer, count As Integer, value As Object, comparer As IComparer) As Integer

參數

index
Int32

要搜尋範圍內之以零為起始的起始索引。

count
Int32

搜尋範圍的長度。

value
Object

要尋找的 Object。 這個值可以是 null

comparer
IComparer

比較項目時所要使用的 IComparer 實作。

-或-

要使用預設比較子的 null 是每個項目的 IComparable 實作。

傳回

如果找到 value,則為已排序的 ArrayListvalue 之以零為起使的索引,否則為負數,即大於 value 的下一個項目索引之位元補數,或者,如果沒有更大的項目,則為 Count 的位元補數。

例外狀況

indexcount 不代表 ArrayList 中的有效範圍。

-或-

comparernull,而且 valueArrayList 的項目都不能實作 IComparable 介面。

comparernullvalue 的類型與 ArrayList 的項目類型不同。

index 小於零。

-或-

count 小於零。

備註

比較子會自定義元素的比較方式。 例如,您可以使用 CaseInsensitiveComparer 實例作為比較子來執行不區分大小寫的字串搜尋。

如果 comparer 已提供 ,則會使用指定的實作,將的 ArrayList 元素與指定的 IComparer 值進行比較。 ArrayList的項目必須已根據 所comparer定義的排序順序,以遞增值排序;否則結果可能不正確。

如果 為 comparernull,則比較是使用 IComparable 專案本身或指定值所提供的實作來完成。 的元素 ArrayList 必須已根據實作所 IComparable 定義的排序順序,以遞增值排序;否則結果可能不正確。

null允許與任何類型比較,且在使用 IComparable時不會產生例外狀況。 排序時, null 會被視為小於任何其他物件。

ArrayList如果 包含多個具有相同值的專案,則方法只會傳回其中一個出現專案,而且可能會傳回任何一個出現專案,不一定傳回第一個專案。

ArrayList如果 不包含指定的值,則方法會傳回負整數。 您可以將位補碼運算 (~) 套用至這個負整數,以取得大於搜尋值的第一個專案索引。 將值插入 至 ArrayList時,這個索引應該當做插入點使用,以維護排序順序。

這個方法是作業 O(log n) ,其中 ncount

另請參閱

適用於