當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


C# List BinarySearch()用法及代碼示例


List <T> .BinarySearch()方法使用二進製搜索算法在已排序的List <T>或其一部分中定位特定元素。此方法的重載列表中有3種方法,如下所示:

    • BinarySearch(T)
    • BinarySearch(T,IComparer <T>)
    • BinarySearch(Int32,Int32,T,IComparer <T>)

BinarySearch(T)方法

此方法使用默認比較器在整個排序後的List <T>中搜索元素,並返回搜索到的元素的從零開始的索引。


用法:

public int BinarySearch (T item);

這裏,item是要定位的對象,item的值可以為null或引用類型。

返回類型:如果找到該項目,則此方法返回要搜索的元素的從零開始的索引,如果找不到,則將返回一個負數,該負數是下一個元素的索引的按位補碼,並且補碼為比那個項目大。如果沒有更大的元素,則將返回Count的按位補碼。

異常:如果默認比較器Default無法找到類型T的IComparable <T>通用接口或IComparable接口的實現,則此方法將提供InvalidOperationException。

以下示例程序旨在說明上述方法的使用:

範例1:

// C# program to illustrate the  
// List<T>.BinarySearch(T) Method 
using System; 
using System.Collections.Generic; 
  
class GFG { 
      
    // Main Method 
    public static void Main() 
    { 
        // List creation 
        List<string> Geek = new List<string>(); 
  
        // List elements 
        Geek.Add("ABCD"); 
        Geek.Add("QRST"); 
        Geek.Add("XYZ"); 
        Geek.Add("IJKL"); 
  
  
        Console.WriteLine("The Original List is:"); 
        foreach(string g in Geek) 
        { 
              
            // prints original List 
            Console.WriteLine(g); 
              
        } 
  
        Console.WriteLine("\nThe List in Sorted form"); 
          
        // sort the List 
        Geek.Sort(); 
      
  
        Console.WriteLine(); 
        foreach(string g in Geek) 
        { 
            // prints the sorted List 
            Console.WriteLine(g); 
              
        } 
  
        Console.WriteLine("\nInsert EFGH:"); 
          
        // insert "EFGH" in the List 
        //"EFGH" insert into its original  
        // position when the List is sorted 
        int index = Geek.BinarySearch("EFGH"); 
          
  
        if (index < 0)  
        { 
              
            Geek.Insert(~index, "EFGH"); 
        } 
  
        Console.WriteLine(); 
          
        foreach(string g in Geek) 
        { 
              
            // prints the sorted list 
            // after inserting "EFGH" 
            Console.WriteLine(g); 
        } 
    } 
}
輸出:
The Original List is:
ABCD
QRST
XYZ
IJKL

The List in Sorted form

ABCD
IJKL
QRST
XYZ

Insert EFGH:

ABCD
EFGH
IJKL
QRST
XYZ

範例2:在此示例中,使用一些整數值創建列表,並使用用戶定義函數使用BinarySearch(T)方法在列表中插入新的整數。

// C# program to illustrate the  
// List<T>.BinarySearch(T) Method 
using System; 
using System.Collections.Generic; 
  
class GFG { 
      
// method for inserting "3" 
public void binarySearch(List<int> Geek) 
{ 
      
    // insert "3" in the List 
    Console.WriteLine("\nInsert 3:"); 
  
    // "3" insert into its original  
    // position when the List is  
    // sorted 
    int index = Geek.BinarySearch(3); 
      
  
    if (index < 0)  
    { 
        Geek.Insert(~index, 3); 
    } 
  
    foreach(int g in Geek) 
    { 
          
        // prints the sorted list 
        // after inserting "3" 
        Console.WriteLine(g); 
          
    } 
} 
} 
  
// Driver Class 
public class search { 
      
    public static void Main() 
    { 
          
        // List creation 
        GFG gg = new GFG(); 
          
        List<int> Geek = new List<int>() { 
                              5, 6, 1, 9}; 
                                
        Console.WriteLine("Original List"); 
      
        foreach(int g in Geek) 
        { 
            Console.WriteLine(g); 
            // prints original List 
        } 
      
        Console.WriteLine("\nList in Sorted form"); 
        Geek.Sort(); 
      
        foreach(int g in Geek) 
        { 
            Console.WriteLine(g); 
            // prints the sorted List 
        } 
      
        // calling the method "binarySearch" 
        gg.binarySearch(Geek); 
    } 
}
輸出:
Original List
5
6
1
9

List in Sorted form
1
5
6
9

Insert 3:
1
3
5
6
9
BinarySearch(T)方法

此方法使用指定的比較器在整個排序列表中搜索元素,並返回搜索到的元素的從零開始的索引。


用法:

public int BinarySearch (T item, System.Collections.Generic.IComparer<T> comparer);

參數:

  • item :這是要查找的項目,對於引用類型,該項目的值可以為null。
  • comparer :比較元素時使用的是IComparer <T>實現。

返回值:如果找到了項,則此方法返回要搜索的元素的從零開始的索引,如果找不到,則返回一個負數,該負數是大於元素的下一個元素的索引的按位補碼,或者沒有更大的元素,Count的按位補碼。

異常:如果比較器為null,並且默認比較器Default找不到類型T的IComparable <T>通用接口或IComparable接口的實現,則此方法將提供InvalidOperationException。

以下示例程序旨在說明上述方法的用法:

範例1:

// C# program to demonstrate the  
// List<T>.BinarySearch(T,  
// IComparer<T>) Method 
using System; 
using System.Collections.Generic; 
  
class GFG:IComparer<string> { 
  
    public int Compare(string x, string y) 
    { 
        if (x == null || y == null)  
        { 
            return 0; 
        } 
        return x.CompareTo(y); 
        //"CompareTo()" method 
    } 
} 
  
// Driver Class 
class geek { 
  
    // Main Method 
    public static void Main() 
    { 
        // list creation 
        List<string> list1 = new List<string>(); 
  
        // list elements 
        list1.Add("B"); 
        list1.Add("C"); 
        list1.Add("E"); 
        list1.Add("A"); 
  
        // prints Original list 
        Console.WriteLine("Original string"); 
  
        foreach(string g in list1) 
        { 
            Console.WriteLine(g); 
        } 
  
        GFG gg = new GFG(); 
  
         // sort the list 
        list1.Sort(gg); 
         
        // prits the sorted form of original list 
        Console.WriteLine("\nList in sorted form"); 
  
        foreach(string g in list1) 
        { 
            Console.WriteLine(g); 
        } 
  
        //"D" is going to insert 
        //"gg" is the IComparer 
        int index = list1.BinarySearch("D", gg); 
         
        if (index < 0)  
        { 
            list1.Insert(~index, "D"); 
        } 
  
        // prints the final List 
        Console.WriteLine("\nAfetr inserting \"D\" in the List"); 
          
        foreach(string g in list1) 
        { 
            Console.WriteLine(g); 
        } 
    } 
}
輸出:
Original string
B
C
E
A

List in sorted form
A
B
C
E

Afetr inserting "D" in the List
A
B
C
D
E

範例2:在本示例中,將使用一些整數值創建列表,並使用用戶定義函數使用BinarySearch(T,Comparer <T>)方法在列表中插入新的整數。

// C# program to demonstrate the  
// List<T>.BinarySearch(T,  
// IComparer<T>) Method 
using System; 
using System.Collections.Generic; 
   
class GFG:IComparer<int> { 
  
    public int Compare(int x, int y) 
    { 
        if (x == 0 || y == 0)  
        { 
            return 0; 
        } 
        return x.CompareTo(y); 
    } 
} 
   
// Driver Class 
class geek { 
  
    // Main Method 
    public static void Main() 
    { 
        // list creation 
        List<int> list1 = new List<int>() { 
                               5, 6, 1, 9}; 
   
        // prints Original list 
        Console.WriteLine("Original string"); 
  
        foreach(int g in list1) 
        { 
            Console.WriteLine(g); 
        } 
   
         // creating object of class GFG 
        GFG gg = new GFG(); 
       
        // sort the list 
        list1.Sort(gg); 
          
        // prits the sorted form  
        // of original list 
        Console.WriteLine("\nList in sorted form"); 
  
        foreach(int g in list1) 
        { 
            Console.WriteLine(g); 
        } 
  
        bSearch b = new bSearch(); 
        b.binarySearch(list1); 
    } 
} 
   
class bSearch { 
  
    public void binarySearch(List<int> list1) 
    { 
  
        // creating object of class GFG 
        GFG gg = new GFG(); 
   
        // "3" is going to insert 
        // "gg" is the IComparer 
        int index = list1.BinarySearch(3, gg); 
          
        if (index < 0)  
        { 
            list1.Insert(~index, 3); 
        } 
   
        // prints the final List 
        Console.WriteLine("\nAfter inserting \"3\" in the List"); 
        foreach(int g in list1) 
        { 
            Console.WriteLine(g); 
        } 
    } 
}
輸出:
Original string
5
6
1
9

List in sorted form
1
5
6
9

After inserting "3" in the List
1
3
5
6
9
BinarySearch(Int32,Int32,T,IComparer <T>)

此方法用於使用指定的比較器在排序後的List <T>中的元素範圍內搜索元素,並返回該元素的從零開始的索引。

用法:

public int BinarySearch (int index, int count, T item, System.Collections.Generic.IComparer<T> comparer);

參數:

  • index:它是要搜索範圍的從零開始的索引。
  • count:這是搜索範圍的長度。
  • item:這是要定位的對象。對於引用類型,該值可以為null。
  • comparer:這是IComparer比較元素時使用的實現,或使用默認比較器Default的null。

返回值:如果找到該項目,它將返回排序後的List <T>中該項目的從零開始的索引;否則,返回0。否則為負數,它是大於元素的下一個元素的索引的按位補數,或者,如果沒有更大的元素,則為Count的按位補數。

異常:

  • ArgumentOutOfRangeException:如果索引小於0或計數小於0。
  • ArgumentException:如果索引和計數不代表有效範圍。
  • InvalidOperationException:如果比較器為null。

例:

// C# program to demonstrate the  
// List<T>.BinarySearch(Int32,  
// Int32, T, Comparer <T>) method 
using System; 
using System.Collections.Generic; 
  
class GFG:IComparer<int> 
{ 
public int Compare(int x, int y) 
{ 
    if (x == 0 || y == 0) 
    { 
        return 0; 
    } 
    return x.CompareTo(y); 
} 
} 
  
class search { 
      
// "binarySearch" function 
public void binarySearch(List<int> list1, 
                                  int i) 
{ 
    Console.WriteLine("\nBinarySearch a "+ 
                   "range and Insert 3"); 
      
    // "gg" is the object of class GFG 
    GFG gg = new GFG(); 
      
    // binary search 
    int index = list1.BinarySearch(0, i, 
                                 3, gg); 
  
  
    if (index < 0) 
    { 
          
        // insert "3" 
        list1.Insert(~index, 3); 
        i++; 
    } 
      
    Display(list1); 
} 
  
// "Display" function  
public void Display(List<int> list)  
{ 
      
    foreach( int g in list ) 
    { 
        Console.WriteLine(g); 
    } 
} 
} 
  
// Driver Class 
class geek 
{ 
      
    // Main Method 
    public static void Main() 
    { 
        List<int> list1 = new List<int>() 
        { 
            // list elements 
            15,4,2,9,5,7,6,8,10 
              
        }; 
      
        int i = 7; 
        Console.WriteLine("Original List"); 
          
        // "d" is the object of  
        // the class "search" 
        search d = new search(); 
          
        // prints Original list 
        d.Display(list1); 
      
        // "gg" is the object  
        // of class GFG  
        GFG gg = new GFG(); 
          
        Console.WriteLine("\nSort a range with "+ 
                       "the alternate comparer"); 
          
        // sort is happens between 
        // index 1 to 7             
        list1.Sort(1, i, gg); 
          
        // prints sorted list 
        d.Display(list1); 
          
        // call "binarySearch" function 
        d.binarySearch(list1,i); 
          
    } 
}
輸出:
Original List
15
4
2
9
5
7
6
8
10

Sort a range with the alternate comparer
15
2
4
5
6
7
8
9
10

BinarySearch a range and Insert 3
15
2
3
4
5
6
7
8
9
10

注意:

  • 如果List <T>包含多個具有相同值的元素,則該方法僅返回一個事件,並且它可能返回任何一個事件,而不一定返回第一個。
  • List <T>必須已經根據比較器實現進行了排序;否則,結果不正確。
  • 此方法是O(log n)運算,其中n是範圍內的元素數。

參考:



相關用法


注:本文由純淨天空篩選整理自SoumikMondal大神的英文原創作品 List BinarySearch() Method in C#。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。